I am building JSON from Java object tree using Jackson ObjectMapper. Some of my Java objects are collections and sometimes they might be empty. So if they are empty that ObjectMapper generates me: "attributes": [], and I want to exclude those kind of empty JSON arrays from my result. My current ObjectMapper config:
SerializationConfig config = objectMapper.getSerializationConfig();
config.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
config.set(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
From this post I've read that I can use:
config.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
But that is generating me an error:
Caused by: java.lang.IllegalArgumentException: Class com.mycomp.assessments.evaluation.EvaluationImpl$1 has no default constructor; can not instantiate default bean value to support 'properties=JsonSerialize.Inclusion.NON_DEFAULT' annotation.
So how should I prevent those empty arrays to appear in my result?
You should use:
config.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
for Jackson 1 or
config.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
for Jackson 2
A very good example describing :
JsonInclude.Include.NON_NULL
JsonInclude.Include.ABSENT
JsonInclude.Include.NON_EMPTY
In : https://www.logicbig.com/tutorials/misc/jackson/json-include-non-empty.html
#JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Employee {
private String name;
private String dept;
private String address;
private List<String> phones;
private AtomicReference<BigDecimal> salary;
.............
}
public class ExampleMain {
public static void main(String[] args) throws IOException {
Employee employee = new Employee();
employee.setName("Trish");
employee.setDept("");
employee.setAddress(null);
employee.setPhones(new ArrayList<>());
employee.setSalary(new AtomicReference<>());
ObjectMapper om = new ObjectMapper();
String jsonString = om.writeValueAsString(employee);
System.out.println(jsonString);
}
}
=====> Result :
If we don't use #JsonInclude annotation at all then output of the above example will be:
{"name":"Trish","dept":"","address":null,"phones":[],"salary":null}
If we use #JsonInclude(JsonInclude.Include.NON_NULL) on Employee class then output will be:
{"name":"Trish","dept":"","phones":[],"salary":null}
If we use #JsonInclude(JsonInclude.Include.NON_ABSENT) then output will be:
{"name":"Trish","dept":"","phones":[]}
If we use #JsonInclude(JsonInclude.Include.NON_EMPTY) :
{"name":"Trish"}
If you can modify the object to be serialized, you can also place an annotation directly on the field, for example (Jackson 2.11.2):
#JsonProperty
#JsonInclude(JsonInclude.Include.NON_EMPTY)
private Set<String> mySet = new HashSet<>();
In this way, no further configuration of the ObjectMapper is required.
Related
I use external application which expects an Object that Serializable from me like his function:
externalFunction(Object input);
So I should give that function an input that will be correctly serialized into JSON when the method is invoked (not controlled by me).
But I don't know how data is structured since I receive input from another external application dynamically. So case like this:
1. Get data from 3rd party
2. MyApp should annotate data for Json Serialization
3. Send data to 3rd party as input
4. Response will be produced as JSON
How can I achieve this? How can I give input to the function that is correctly serialized when the function is invoked?
What I tried so far:
So first thing I try is wrap data with some Wrapper like:
public class JsonWrapper<T> implements Serializable
{
public T attributes;
public JsonWrapper( T attributes )
{
this.attributes = attributes;
}
#JsonValue
public T getAttributes( )
{
return attributes;
}
}
So I wrap data like ->
data = getFromThirdParty();
wrapped = new JsonWrapper<>(data);
externalFunction(wrapped);
But it produces a response with "attributes" field which I don't want. Also I tried to use #JsonUnwrapped public T attributes; but the result is same.
I don't want this:
{
"attributes": {
... some fields/values that I don't know, get from 3rd party
}
}
I want like this:
{
... some fields/values that I don't know, get from 3rd party
}
The #JsonUnwrapped annotation doesn't work when T is a Collection (see this answer from the Jackson's creator). But the #JsonValue annotation actually does the trick:
public class JsonWrapper<T> {
#JsonValue
private T value;
public JsonWrapper(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
If you use Lombok, you can have:
#Getter
#AllArgsConstructor
public class JsonWrapper<T> {
#JsonValue
private T value;
}
Example
Consider the following class:
#Data
#AllArgsConstructor
public class Person {
private String firstName;
private String lastName;
}
When serializing an Person instance, the following result JSON is produced:
ObjectMapper mapper = new ObjectMapper();
JsonWrapper<?> wrapper = new JsonWrapper<>(new Person("John", "Doe"));
String json = mapper.writeValueAsString(wrapper);
{"firstName":"John","lastName":"Doe"}
When serializing a list of Person instances, the following result JSON is produced:
ObjectMapper mapper = new ObjectMapper();
JsonWrapper<?> wrapper = new JsonWrapper<>(
Arrays.asList(
new Person("John", "Doe"),
new Person("Jane", "Poe")
));
String json = mapper.writeValueAsString(wrapper);
[{"firstName":"John","lastName":"Doe"},{"firstName":"Jane","lastName":"Poe"}]
I have a map that unsure it keys,but I am sure the keys contains all the pojo fields, says:
public class MyPojo{
String name,
String addr
}
//map contains keys that not in MyPojo field,e.g. age
map = {"name":"john","addr":"sf school","age":"21"}
In Java how can I can convert it to pojo MyPojo instance? the following method throw exception:
final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);
You can use #JsonIgnoreProrperties by Jackson in your MyPojo class.
The exception is cause of ObjectMapper not being able to find exact mapping in your MyPojo class.
The API is provided in the same library, that of ObjectMapper.
So here is what your class should look like:
#JsonIgnoreProperties(ignoreUnknown = true)
public class MyPojo{
String name;
String addr;
//Other variables
}
To import it in your code, you need to add the following:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
I hope this solves your problem and thisis exactly what you're looking for.
As you are working on generics keys(previously unknown), there might be chances of keys(attribute names) present in the map as a key doesn't present in POJO as an attribute. So, set below properties to false, when you create an ObjectMapper instance, so that any unknown or missing attributes wouldn't throw any exceptions.
final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
i'm using Jersey to build a REST service and as Json Processor i set Jackson in my application.
#javax.ws.rs.ApplicationPath("/")
public class MyApplication extends ResourceConfig {
public MyApplication() {
packages("controller");
register(JacksonFeature.class);
}
I implement a ContextResolver for Jacksons ObjectMapper (as it's suggested in this post Configure Jersey/Jackson to NOT use #XmlElement field annotation for JSON field naming) which creates an ObjectMapper that doesn't fail on unknown properties during deserialization:
#Provider
public class MyJsonObjectMapperProvider implements ContextResolver<ObjectMapper> {
#Override
public ObjectMapper getContext(Class<?> type)
{
System.out.println("mapper!!!");
ObjectMapper result = new ObjectMapper();
result.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return result;
}
}
and then i register this class in my application inserting register(MyJsonObjectMapperProvider.class) in the class MyApplication shown above. I obtain what i want, in sense that if there are unknown properties in the json the object mapper doesn't fail.
My problem is another; i have this class that i use to map a specified Json, in order to deserialize it and subsequently serialize it:
public class Version {
private String status;
private String updated;
private String id;
private List<Link> links;
#XmlElement(name = "media-types")
private List<MediaTypes> media_types;
//constructor + getter and setter
}
The problem is about the element media_types and the use of the annotation #XmlElement. Before i insert the ContextResolver to personalize ObjectMapper all works fine, in fact after serialization i obtain a json in which the element/attribute media_types has as name media-types; on the contrary with ContextResolver this element doesn't change it's name and has media_types. I think that, during serialization, the annotation XmlElement doesn't work, but i'm not sure that this is the correct reason.
Another attempt i try to do is to put #JsonProperty("media-types") annotation instead of #XmlElement annotation but with no result; in fact with this annotation i obtain also a Processing Exception.
The last attempt (in addition to what has been suggested by the previous post) was that of insert these lines of code in the ContextResolver:
AnnotationIntrospector intr = new AnnotationIntrospector.Pair(new JaxbAnnotationIntrospector(),new JacksonAnnotationIntrospector());
// usually we use same introspector(s) for both serialization and deserialization:
result.getDeserializationConfig().withAnnotationIntrospector(intr);
result.getSerializationConfig().withAnnotationIntrospector(intr);
in order to use both JaxbAnnotation and JacksonAnnotation but the name of the field in question remain media_types.
I hope i was clear in explain my problem and thanks you in advance for your help!
I have a light wrapper class around a complex class for which I needed to write a custom Jackson JSON deserializer. The wrapper class is simple and only contains a String, a Date, and my complex object as properties. Does Jackson automatically apply a simple deserializer to the wrapper and my custom deserializer to my complex object? The custom deserializer works by itself. But when I try to serialize the wrapper Jackson throws a Nullpointer Exception. I must be missing something conceptual. Do I have to register another serializer with my module in addition to my custom deserializer?
java.lang.NullPointerException
at org.codehaus.jackson.impl.ReaderBasedParser._skipWSOrEnd(ReaderBasedParser.java:1477)
at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(ReaderBasedParser.java:368)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:690)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1863)
at com.newoak.noc.curve.model.tests.ModelParamsTest.deserializeGraph(ModelParamsTest.java:100)
at com.newoak.noc.curve.model.tests.ModelParamsTest.testSerializationDeserialization(ModelParamsTest.java:113)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
Trying to deserialize
public ModelParamGraph deserializeGraph(String json) throws JsonGenerationException, JsonMappingException, IOException
{
ObjectMapper mapper = new ObjectMapper();
SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null));
testModule.addSerializer(new SpaceJsonSerializer());
testModule.addDeserializer(Space.class, new SpaceJsonDeserializer());
mapper.registerModule(testModule);
ModelParamGraph space = mapper.readValue(json, ModelParamGraph.class);
return space;
}
Wrapper
public class ModelParamGraph
{
public String source;
public Date date;
#JsonSerialize(using=SpaceJsonSerializer.class)
#JsonDeserialize(using=SpaceJsonDeserializer.class)
public Space<TModelParam> paramSpace;
public ModelParamGraph()
{
}
public ModelParamGraph(String source, Date date)
{
setSource(source);
setDate(date);
setParamSpace(new Space<TModelParam>());
}
//getters and setters
}
If you can modify the class being wrapped, then you can use Jackson's #JsonView annotation, here is the full tutorial.
Step 1: create interfaces like so:
public class MyJsonViews {
public static class Small { }
public static class Medium extends Small { }
public static class Large extends Medium { }
}
Step 2: annotate properties (or methods) in your POJOs:
public class Wrapper {
#JsonView(MyJsonViews.Small.class)
private String name;
#JsonView(MyJsonViews.Medium.class)
private Wrapped wrapped;
// getters and setters
}
public class Wrapped {
#JsonView(MyJsonViews.Small.class)
private String someField;
#JsonView(MyJsonViews.Medium.class)
private String anotherField;
// getters and setters
}
Step 3: serialize using the new views:
ObjectMapper objectMapper = new ObjectMapper();
// important: this excludes all fields without #JsonView from being serialized
objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
String json = objectMapper.writerWithView(SMyJsonViews.mall.class).writeValueAsString(wrapper);
Your JSON will now contain just the fields annotated with #JsonView(MyJsonViews.Small.class).
If you cannot modify the class being wrapped, then you could use the Filter approach, described here.
I need to configure Jackson in a specific way which I'll describe below.
Requirements
Annotated fields are serialized with only their id:
If the field is a normal object, serialize its id
If the field is a collection of objects, serialize an array of id
Annotated fields get their property names serialized differently:
If the field is a normal object, add "_id" suffix to property name
If the field is a collection of objects, add "_ids" suffix to property name
For the annotation I was thinking something like a custom #JsonId, ideally with an optional value to override the name just like #JsonProperty does
The id property should be defined by the user, either using:
The already existing Jackson's #JsonIdentityInfo
Or by creating another class or field annotation
Or by deciding which annotation to inspect for id property discoverability (useful for JPA scenarios, for example)
Objects should be serialized with a wrapped root value
Camel case naming should be converted to lower case with underscores
All of this should be deserializable (by constructing an instance with just the id setted)
An example
Considering these POJO's:
//Inform Jackson which property is the id
#JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id"
)
public abstract class BaseResource{
protected Long id;
//getters and setters
}
public class Resource extends BaseResource{
private String name;
#JsonId
private SubResource subResource;
#JsonId
private List<SubResource> subResources;
//getters and setters
}
public class SubResource extends BaseResource{
private String value;
//getters and setters
}
A possible serialization of a Resource instance could be:
{
"resource":{
"id": 1,
"name": "bla",
"sub_resource_id": 2,
"sub_resource_ids": [
1,
2,
3
]
}
}
So far...
Requirement #5 can be accomplished by configuring ObjectMapper in the following way:
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
And then using #JsonRootName("example_root_name_here") in my POJO's.
Requirement #6 can be accomplished by configuring ObjectMapper in the following way:
objectMapper.setPropertyNamingStrategy(
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
As you can see there are still lots of requirements to fulfill. For those wondering why I need such a configuration, it's because I'm developing a REST webservice for ember.js (more specifically Ember Data).
You would appreciate very much if you could help with any of the requirements.
Thanks!
Most (all?) of your requirements can be accomplished through the use of a contextual serializer. Taking one answer from ContextualDeserializer for mapping JSON to different types of maps with Jackson and Jackson's wiki (http://wiki.fasterxml.com/JacksonFeatureContextualHandlers) I was able to come up with the following.
You need to start with the #JsonId annotation, which is the key indicating a property needs to only use the Id property.
import com.fasterxml.jackson.annotation.*;
import java.lang.annotation.*;
#Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#JacksonAnnotation // important so that it will get included!
public #interface JsonId {
}
Next is the actual ContextualSerializer, which does the heavy lifting.
import com.fasterxml.jackson.databind.ser.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.core.*;
import java.io.*;
public class ContextualJsonIdSerializer
extends JsonSerializer<BaseResource>
implements ContextualSerializer/*<BaseResource>*/
{
private ObjectMapper mapper;
private boolean useJsonId;
public ContextualJsonIdSerializer(ObjectMapper mapper) { this(mapper, false); }
public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
this.mapper = mapper;
this.useJsonId = useJsonId;
}
#Override
public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider) throws IOException
{
if ( useJsonId ) {
jgen.writeString(br.getId().toString());
} else {
mapper.writeValue(jgen, br);
}
}
#Override
public JsonSerializer<BaseResource> createContextual(SerializerProvider config, BeanProperty property)
throws JsonMappingException
{
// First find annotation used for getter or field:
System.out.println("Finding annotations for "+property);
if ( null == property ) {
return new ContextualJsonIdSerializer(mapper, false);
}
JsonId ann = property.getAnnotation(JsonId.class);
if (ann == null) { // but if missing, default one from class
ann = property.getContextAnnotation(JsonId.class);
}
if (ann == null ) {//|| ann.length() == 0) {
return this;//new ContextualJsonIdSerializer(false);
}
return new ContextualJsonIdSerializer(mapper, true);
}
}
This class looks at BaseResource properties and inspects them to see if the #JsonId annotation is present. If it is then only the Id property is used, otherwise a passed in ObjectMapper is used to serialize the value. This is important because if you try to use the mapper that is (basically) in the context of the ContextualSerializer then you will get a stack overflow since it will eventually call these methods over and over.
You're resource should look something like the following. I used the #JsonProperty annotation instead of wrapping the functionality in the ContextualSerializer because it seemed silly to reinvent the wheel.
import java.util.*;
import com.fasterxml.jackson.annotation.*;
public class Resource extends BaseResource{
private String name;
#JsonProperty("sub_resource_id")
#JsonId
private SubResource subResource;
#JsonProperty("sub_resource_ids")
#JsonId
private List<SubResource> subResources;
//getters and setters
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public SubResource getSubResource() {return subResource;}
public void setSubResource(SubResource subResource) {this.subResource = subResource;}
public List<SubResource> getSubResources() {return subResources;}
public void setSubResources(List<SubResource> subResources) {this.subResources = subResources;}
}
Finally the method that performs the serialization just creates an additional ObjectMapper and registers a module in the original ObjectMapper.
// Create the original ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
// Create a clone of the original ObjectMapper
ObjectMapper objectMapper2 = new ObjectMapper();
objectMapper2.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
objectMapper2.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
objectMapper2.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
// Create a module that references the Contextual Serializer
SimpleModule module = new SimpleModule("JsonId", new Version(1, 0, 0, null));
// All references to SubResource should be run through this serializer
module.addSerializer(SubResource.class, new ContextualJsonIdSerializer(objectMapper2));
objectMapper.registerModule(module);
// Now just use the original objectMapper to serialize