Jackson Data-Binding with Heterogeneous Json Object - java

I'm calling a rest service that returns a json object. I'm trying to deserialize the responses to my Java Beans using Jackson and data-binding.
The example Json is something like this:
{
detail1: { property1:value1, property2:value2},
detail2: { property1:value1, property2:value2},
otherObject: {prop3:value1, prop4:[val1, val2, val3]}
}
Essentially, detail1 and detail2 are of the same structure, and thus can be represented by a single class type, whereas OtherObject is of another type.
Currently, I've set up my classes as follows (this is the structure I would prefer):
class ServiceResponse {
private Map<String, Detail> detailMap;
private OtherObject otherObject;
// getters and setters
}
class Detail {
private String property1;
private String property2;
// getters and setters
}
class OtherObject {
private String prop3;
private List<String> prop4;
// getters and setters
}
Then, just do:
String response = <call service and get json response>
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(response, ServiceResponse.class)
The problem is I'm getting lost reading through the documentation about how to configure the mappings and annotations correctly to get the structure that I want. I'd like detail1, detail2 to create Detail classes, and otherObject to create an OtherObject class.
However, I also want the detail classes to be stored in a map, so that they can be easily distinguished and retrieved, and also the fact that the service in in the future will return detail3, detail4, etc. (i.e., the Map in ServiceResponse would look like
"{detail1:Detail object, detail2:Detail object, ...}).
How should these classes be annotated? Or, perhaps there's a better way to structure my classes to fit this JSON model? Appreciate any help.

Simply use #JsonAnySetter on a 2-args method in ServiceResponse, like so:
#JsonAnySetter
public void anySet(String key, Detail value) {
detailMap.put(key, value);
}
Mind you that you can only have one "property" with #JsonAnySetter as it's a fallback for unknown properties. Note that the javadocs of JsonAnySetter is incorrect, as it states that it should be applied to 1-arg methods; you can always open a minor bug in Jackson ;)

Related

Jackson: passing exta objects during deserialization

During deserialization, how can I pass in an extra object that's needed to initialize some class member? If I were doing deserialization "manually," the implementation might look like:
public class MyClass {
private MyDocumentObject do;
private String food;
public MyClass(JsonNode node, MyDocument document) {
this.do = document.createMyDocumentObject();
this.food = node.get("food").asText();
}
public String getFood() {
return this.food;
}
}
But I'd like to use Jackson's automatic mapping facilities and use a decorated constructor or custom deserializer, etc. and avoid implementing the deserialization within the class itself. Looking at example implementations using #JsonCreator or extending StdDeserializer, I can't see a way of saying "hey, please use this MyDocument object when you call the constructor." I'd like to avoid implementing and exposing a separate method that accepts a MyDocument that I have to invoke on every object that gets deserialized, e.g.
public createDocumentObject(MyDocument document) {
this.do = document.createMyDocumentObject();
}
I don't want to have this method at all, but if I had to, I'd want Jackson to call this method for me right after deserialization. That means I'd still have to somehow tell Jackson which MyDocument to use.

In Java, how can I map a string that is either JSON or XML to the same POJO, but with the XML having one different field/attribute name from the JSON?

I am currently using Jackson's XmlMapper and ObjectMapper. I want to map the string to a POJO (I think I'm using that term correctly) that has a private field with the same name as the JSON string's field. The XML string has a different name for the same field/attribute, and I want to use the JSON field name.
I also want to essentially "ignore" that field (while keeping it) and store it as something like a JsonNode, as the value of that field can be some complex, nested value without a known shape.
Example:
public static class OuterClass {
private String firstValue;
private InnerClass innerValue;
// ... getters/setters
}
public static class InnerClass {
private JsonNode data; // complex, nested, so no POJO to map to
private String otherValue;
// ... getters/setters
}
The JSON might look like this:
{
"innerValue": {
"data": {
... complex stuff
},
"otherValue": "more stuff"
},
"firstValue": "thingy"
}
The XML might look like this:
<result>
<innerValue>
<incorrectName>
... complex stuff
</incorrectName>
<otherValue>more stuff</otherValue>
</innerValue>
<firstValue>thingy</firstValue>
</result>
So the goal is to get the XML to work with that class, including both mapping incorrectName to the class' data, as well as storing the complex inner part as something like a JsonNode since I don't have a class to model it.
I have the JSON working with new ObjectMapper().readValue(jsonString, OuterClass.class), and I think the XML should work with new XmlMapper().readValue(xmlString, OuterClass.class), but I don't know where to go with annotations. I've looked at the different annotations available and I don't think I've found the right one. I've also read that I shouldn't convert XML to a JsonNode, as there can be problems with that. I don't need to convert it back to XML after, though, and can treat it as JSON once I receive the JSON/XML string. So, I'd appreciate some help, thanks!
#XmlAccessorType(XmlAccessType.PROPERTY)
public static class InnerClass {
private JsonNode data; // complex, nested, so no POJO to map to
private String otherValue;
// ... getters/setters
#XmlElement(name = "incorrectName")
protected JsonNode getData() {return data;}
}

Wrapping Json fields into instance variable of a pojo

i am trying to map certain json fields to a class instance variable.
My sample Person class looks like:
public class Person {
private String name;
private Address address;
//many more fields
//getters and setters
}
The sample Address class is:
public class Address {
private String street;
private String city;
//many more fields
// getters and setters
}
The json object to be deserialized to my Person class doesn't contain "address" field. It looks like:
{
"name":"Alexander",
"street":"abc 12",
"city":"London"
}
Is there a way to deserialize the json to the Person pojo where the Address fields are also mapped properly?
I have used a custom Address deserializer as mentioned in so many posts here. However, it's not being called as the Json object doesn't contain "address" field.
I had resolved this problem by mapping each field manually using JsonNode, however in my real project, it's not a nice solution.
Is there any work around for such problem using jackson?
Plus if this question has been asked before then apologies on my behalf as as i have intensively searched for the solution and might have not seen it yet. .
#JsonUnwrapped annotation was introduced for this problem. Model:
class Person {
private String name;
#JsonUnwrapped
private Address address;
// getters, setters, toString
}
class Address {
private String street;
private String city;
// getters, setters, toString
}
Usage:
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"Alexander\",\"street\":\"abc 12\",\"city\":\"London\"}";
System.out.println(mapper.readValue(json, Person.class));
Prints:
Person{name='Alexander', address=Address{street='abc 12', city='London'}}
For more info read:
Jackson Annotation Examples
Annotation Type JsonUnwrapped
Jackson JSON - Using #JsonUnwrapped to serialize/deserialize properties as flattening data structure
I don't think you really have a deserialization problem here but rather a general Java problem: how to make sure the address field always contains a value. All you need to do is either assign address to a default value in the Person constructor, or generate and assign a default value for address in the Person.getAddress method.
I understood your problem so that it is about flat Json that has all Address fields at the same level as Person. Even if it is not exactly so this might help you. JsonDeserializer will do fine but you need to apply it to Person because it is the level where all the fields are.
So like this:
public class CustomDeserializer extends JsonDeserializer<Person> {
// need to use separate ObjectMapper to prevent recursion
// this om will not be registered with this custom deserializer
private final ObjectMapper om;
{
om = new ObjectMapper();
// this is needed because flat json contains unknown fields
// for both types.
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
#Override
public Person deserialize(JsonParser parser, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
// make a string of json tree so not any particular object
String json = om.readTree(parser).toString();
// deserialize it as person (ignoring unknown fields)
Person person = om.readValue(json, Person.class);
// set address deserializing it from teh same string, same manner
person.setAddress(om.readValue(json, Address.class));
return person;
}
}
Of course this is not the only way and might not have the best performance but it is only about how you do the deserialization in your custom deserializer. If your Person & Address objects are havin like 10 fields each using this should not be a problem.
Update
I think that in your case - based on your example data - Michał Ziober's
answer might be the best but if you need any more complex handling than plain unwrapping for your data you just need to deserialize Person class somehow like I presented.

Can the JsonProperty required value be conditional?

Is it possible to have the #JsonProperty required dynamically set or set at call?
The reason behind this...
I'm generating json files which describes a schema and defines
What are the required fields for a new item
What are the required fields for an update to an item.
So, a creation requires only foo
and an update requires foo and bar
Can I make things so I can pass in something to say bar is now required?
or would I need to duplicate this code in order to have different settings for JsonProperty?
#JsonInclude(Include.NON_NULL)
public class Bean {
#JsonProperty(value="foo", required=false)
private FooProperty fooProperty;
#JsonProperty(value="bar", required=false)
private BarProperty barProperty;
//
public FooProperty getFooProperty() { return fooProperty; }
public void setFooProperty(FooProperty argFooProperty) {
this.fooProperty = argFooProperty
}
public BarProperty getBarProperty() { return barProperty; }
public void setFooProperty(BarProperty argBarProperty) {
this.barProperty = argBarProperty
}
}
You could solve this issue in couple of ways. First one would be as Franjavi suggested you could use a mixin.
Have a mixin class which will mark your foo as one of the ignored properties. In your main class mark both the fiends required and you can inject this mixin whenever this is an option field.
#JsonIgnoreProperties("foo")
public abstract class mixinClass {
}
You configure your mixin into your mapper as follows.
ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Bean.class, mixinClass.class);
This is not always a working option whenever you are getting this response from a third party API where you might be serializing/deserializing using the default jackson mapper which are provided by them like Resttemplate.
In this case, instead of having the foo property, you can just included whatever the properties that are present in all the responses and handle the rest of the properties using #JsonAnyGetter and #JsonAnySetter. You can capture this in a map with key being your object name which is in this case foo. You need to have the following part in your parent node or whichever node that will encapsulates these optional properties.
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
Let me know if you need any further clarification!!
You can play wiht Mixins and the mapper:
public interface BarRequiredMixIn {
#JsonProperty(value="bar", required=true)
private BarProperty barProperty;
}
ObjectMapper mapper = new ObjectMapper();
// When you want that it is required
mapper.addMixInAnnotations(Bean.class, BarRequiredMixIn.class);
But I strongly recommend to avoid to use this kind of conditional restrictions with Jackson, since it is not designed for it, and it looks kind of confusing.
Based on the example you have given, setting the following in your POJO would be sufficient & Jackson would be able to figure out whether to deserialize it/not . All #JsonProperty are required by default, so with the code below, you would be able to achieve optional bar value in your Create/Update scenarios based on payload in the request
#JsonProperty(value="bar", required=false)
private Bar bar;

Xstream: Implicitly ignoring all fields

How do I tell Xstream to serialize only fields which are annotated explicitly and ignore the rest?
I am trying to serialize a hibernate persistent object and all proxy related fields get serialized which I don’t want in my xml.
e.g.
<createdBy class="com..domain.Users " reference="../../values/createdBy"/>
is not something I want in my xml.
Edit: I don’t think I made this question clear. A class may inherit from a base class on which I have no control (as in hibernate’s case) on the base class properties.
public class A {
private String ShouldNotBeSerialized;
}
public class B extends A {
#XStreamAlias("1")
private String ThisShouldbeSerialized;
}
In this case when I serialize class B, the base class field ShouldNotBeSerialized will also get serialized. This is not something I want. In most circumstances I will not have control on class A.
Therefore I want to omit all fields by default and serialize only fields for which I explicitly specify the annotation. I want to avoid what GaryF is doing, where I need to explicitly specify the fields I need to omit.
You can omit fields with the #XstreamOmitField annotation. Straight from the manual:
#XStreamAlias("message")
class RendezvousMessage {
#XStreamOmitField
private int messageType;
#XStreamImplicit(itemFieldName="part")
private List<String> content;
#XStreamConverter(SingleValueCalendarConverter.class)
private Calendar created = new GregorianCalendar();
public RendezvousMessage(int messageType, String... content) {
this.messageType = messageType;
this.content = Arrays.asList(content);
}
}
I can take no credit for this answer, just sharing what I have found. You can override the wrapMapper method of the XStream class to achieve what you need.
This link explains in detail: http://pvoss.wordpress.com/2009/01/08/xstream/
Here is the code you need if you don't want the explanation:
// Setup XStream object so that it ignores any undefined tags
XStream xstream = new XStream() {
#Override
protected MapperWrapper wrapMapper(MapperWrapper next) {
return new MapperWrapper(next) {
#Override
public boolean shouldSerializeMember(Class definedIn,
String fieldName) {
if (definedIn == Object.class) {
return false;
}
return super
.shouldSerializeMember(definedIn, fieldName);
}
};
}
};
You might want to do all your testing before you implement this code because the exceptions thrown by the default XStream object are useful for finding spelling mistakes.
There was already a ticket for the XStream people:
Again, this is by design. XStream is a serialization tool, not a data
binding tool. It is made to serialize Java objects to XML and back. It
will write anything into XML that is necessary to recreate an equal
object graph. The generated XML can be tweaked to some extend by
configuration for convenience, but this is already an add-on. What you
like to do can be done by implementing a custom mapper, but that's a
question for the user's list and cannot be handled here.
http://jira.codehaus.org/browse/XSTR-569
I guess the only direct way is to dive into writing a MapperWrapper and exclude all fields you have not annotated. Sounds like a feature request for XStream.

Categories