I can't find any explanation about difference between jackson's ObjectMapper to other mappers like dozer/mapStruct/modelMapping/etc. All the articles compare dozer/mapStruct/modelMapping but they ignore ObjectMapper. I can't understand what is wrong? Is the same mapper?
Dozer, MapStruct and ModelMapping are Java Bean to Java Bean mappers frameworks that recursively copies data from one object to another, property by property, field by field.
From other side, ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs, or to and from a general-purpose JSON Tree Model. ObjectMapper has some additional features like converting objects (see convertValue method) but it is not a main reason why this class was created.
So, if you want to implement sophisticated mapping between two different models you should use mappers; if you want to serialise model to JSON or deserialise model from JSON payload you have to use ObjectMapper from Jackson.
Jackson library- Mainly concerned with converting Objects/ Entities to JSON and back.
ModelMapper/ MapStruct - Concerned with mapping One entity to another like, mapping an Entity to its DTO. This operation can get pretty gnarly owing to the size and complexity of different entities, so we need these libraries to make work easier.
Related
I am trying to think of scenario to use Jackson TreeModel and Databinding API (Object mapper). When you would chose one again the another ?
URL-es you added to a question contain the answer in the overview.
Working with Tree Model
We’ll use JsonNode for various conversions as well as adding,
modifying and removing nodes.
and
Intro to the Jackson ObjectMapper
This write-up is focused on understanding the Jackson ObjectMapper
class – and how to serialize Java objects into JSON and deserialize
JSON string into Java objects.
I can only confirm that. 99% of examples I had to serialize Java POJO classes to JSON and vice versa. When I need to change a little JSON I use Tree Model to avoid whole serializing and deserializing process.
I need to provide a different version of response object for the same existing URI. I am going with Accept/Content-type conneg methodologies. I am using Jackson to covert my POJO into json. please help me how should i do it with jackson.
for the object model, must i have a base class and object versions are extended class?
Instead of having one object that would be serialized in two different ways, I'd recommend using two separate DTOs. One for each version.
The content negotiation will happen not on Jackson's side, but on the JAX-RS side with the #Produces annotation.
One method returning DTOv1 will produce application/vnd.v1+json while the other will return DTOv2 with application/vnd.v2+json.
I'm trying to do some polymorphic deseralization of JSON using Jackson, however the list of subclasses is unknown at compile time, so I can't use a #JsonSubtype annotation on the base class.
Instead I want to use a TypeIdResolver class to perform the conversion to and from a property value.
The list of possible subclasses I might encounter will be dynamic, but they are all registered at run time with a registry. So I would appear to need my TypeIdResolver object to have a reference to that registry class. It has to operate in what is essentially a dependency injection environment (i.e I can't have a singleton class that the TypeIdResolver consults), so I think I need to inject the registry class into the TypeIdResolver. The kind of code I think I want write is:
ObjectMapper mapper = new ObjectMapper();
mapper.something(new MyTypeIdResolver(subclassRegistry));
mapper.readValue(...)
However, I can't find a way of doing the bit in the middle. The only methods I can find use java annotations to specify what the TypeIdResolver is going to be.
This question Is there a way to specify #JsonTypeIdResolver on mapper config instead of annotation? is the same, though the motivation is different, and the answer is to use an annotation mixin, which won't work here.
SimpleModule has method registerSubtypes(), with which you can register subtypes. If only passing Classes, simple class name is used as type id, but you can also pass NamedType to define type id to use for sub-class.
So, if you do know full set, just build SimpleModule, register that to mapper.
Otherwise if this does not work you may need to resort to just sharing data via static singleton instance (if applicable), or even ThreadLocal.
Note that in the end what I did was abandon Jackson and write my own much simpler framework based on javax.json that just did the kinds of serialisation I wanted in a much more straightforward fashion. I was only dealing with simple DTO (data transfer object) classes, so it was just much simpler to write my own simple framework.
Can someone point me to a good explanation of the criteria a class must meet to use the default deserializaton for Jackson?
I can do a post and supply a HashMap collection of string/jsonObjects, but it won't work with a dataset that contains the same information in a row. I tried implementing my own Deserializer but the response is always "Unprocessable Entity". I have been successful using specific classes, but I am trying to generalize my solution by passing a dataset.
Obviously I need a better understanding of what is happening! TIA!
It depends on rough type of your class. Jackson has specialized handling for:
Arrays of types
Collection implementations
Map implementations
Enums
Other
If type is none of first 4 categories, it will be considered "Other", and expected to follow Java Bean convention of either public fields, or getters and/or setters.
There also has to be a no-argument constructor (need not be public), or another constructor annotated with #JsonCreator -- expect that some public single-argument constructors (String, int/Integer, long/Long, boolean/Boolean) are also accepted when binding from JSON Scalar values.
But to get more information you really should share the actual exception you get: above is just the general idea of what is needed. Jackson can work with all kinds of classes, and is not particularly strict in how classes are defined. But it does have expectations on how various JSON Structures match with POJOs.
In my web method, I get an object of some third party C# entity class. The entity class is nothing but the DataContract. This entity class is quite complex and has properties of various types, some properties are collections too. Of course, those linked types are also DataContracts.
I want to serialize that DataContract entity into XML as part of business logic of my web service. I cannot use DataContractSerializer directly (on the object I receive in the web method) simply because the XML schema is altogether different. So the XML generated by DataContractSerializer will not get validated against the schema.
I am not able to conclude the approach I should follow for implementation. I could think of following implementation approaches:
LINQ to XML - This looks ok but I need to create XML tree (i.e. elements or XML representation of the class instance) manually for each type of object. Since there are many entity classes and they are linked to each other, I think this is too much of work to write XML elements manually. Besides, i'll have to keep modifying the XML Tree as and when the entity class introduces some new property. Not only this, the code where I generate XML tree would look little clumsy (at least in appearance) and would be harder to maintain/change by some other developer in future; he/she will have to look at it so closely to understand how that XML is generated.
XmlSerializer - I can write my own entity classes that represent the XML structure I want. Now, I need to copy details from incoming object to the object of my own classes. So this is additional work (for .NET too when code executes!). Then I can use XmlSerializer on my object to generate XML. In this case, I'll have to create entity classes and whenever third party entity gets modified, I'll have to just add new property in my class. (with XmlElement or XmlAttibute attributes). But people recommend DataContractSerializer over this one and so I don't want to finalize this unless all aspects are clear to me.
DataContractSerializer - Again here, I'll have to write my own entity class since I have no control over the third party DataContracts. And I need to copy details from incoming object to the object of my own classes. So this is additional work. However, since DataContractSerializer does not support Xml attributes, I'll have to implement IXmlSerializable and generate required Xml in WriteXml method. DataContractSerializer is faster than XmlSerializer, but again I'll have to handle the changes (in WriteXml) if third party entity changes.
Questions:
Which approach is best in this scenario considering performance too?
Can you suggest some better approach?
Is DataContractSerializer worth considering (because it has better performance over XmlSerilaizer) when incoming entity class is subject to change?
Should LINQ be really used for serialization? Or is it really good for things other than querying?
Can XmlSerializer be preferred over LINQ in such cases? If yes, why?
I agree with #Werner Strydom's answer.
I decided to use the XmlSerializer because code becomes maintainable and it offers performance I expect. Most important is that it gives me full control over the XML structure.
This is how I solved my problem:
I created entity classes (representing various types of Xml elements) as per my requirement and passed an instance of the root class (class representing root element) through XmlSerializer.
Small use of LINQ in case of 1:M relationship:
Wherever I wanted same element (say Employee) many times under specific node (say Department) , I declared the property of type List<T>. e.g. public List<Employee> Employees in the Department class. In such cases XmlSerializer obviously added an element called Employees (which is grouping of all Employee elements) under the Department node. In such cases, I used LINQ (after XmlSerializer serialized the .NET object) to manipulate the XElement (i.e. XML) generated by XmlSerializer. Using LINQ, I simply put all Employee nodes directly under Department node and removed the Employees node.
However, I got the expected performance by combination of xmlSerializer and LINQ.
Downside is that, all classes I created had to be public when they could very well be internal!
Why not DataContractSerializer and LINQ-to-XML?
DataContractSerializer does not allow to use Xml attributes (unless I implement IXmlSerializable). See the types supported by DataContractSerializer.
LINQ-to-XML (and IXmlSerializable too) makes code clumsy while creating complex XML structure and that code would definitely make other developers scratch their heads while maintaining/changing it.
Is there any other way?
Yes. As mentioned by #Werner Strydom, you can very well generate classes using XSD.exe or tool like Xsd2Code and work directly with them if you are happy with the resulting classes.
I'll pick XmlSerializer because its the most maintainable for a custom schema (assuming you have the XSD). When you are done developing the system, test its performance in its entirety and determine whether XML serialization is causing problems. If it is, you can then replace it with something that requires more work and test it again to see if there is any gains. But if XML serialization isn't an issue, then you have maintainable code.
The time it takes to parse a small snippet of XML data may be negligible compared to communicating with the database or external systems. On systems with large memory (16GB+) you may find the GC being a bottleneck in .NET 4 and earlier (.NET 4.5 tries to solve this), especially when you work with very large data sets and streams.
Use AutoMapper to map objects created by XSD.EXE to your entities. This will allow the database design to change without impacting the web service.
One thing that is great about LINQ to XML is XSD validation. However, that impacts performance.
Another option is to utilize LINQ and Reflection to create a generic class to serialize your object to XML. A good example of this can be found at http://primecoder.blogspot.com/2010/09/how-to-serialize-objects-to-xml-using.html . I am not sure what your XML needs to look like at the end of the day, but if it is pretty basic this could do the trick. You would not need to make changes as your entity classes add/remove/change properties, and you could use this across all of your objects (and other projects if stored in a utility DLL).