Can I use a DataSet as my Entity? - jackson

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.

Related

Jackon JSON: Polymorphic deseralization when subclasses are unknown

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.

Jackson BeanSerializerModifier.modifySerializer & interfaces that modify how a JsonSerializer is handled

Some interfaces, like ResolvableSerializer & ContextualSerializer, modify how Jackson handles a JsonSerializer.
Are there any other such interfaces?
Does Jackson ever modify its behavior for subclasses of JsonSerializer, like StdSerializer, BeanSerializerBase, or BeanSerializer? (other than via standard polymorphism, of course; I'm talking about things like instanceof, or Class.isAssignableFrom(), etc.)
In an implementation of modifySerializer in a subclass of BeanSerializerModifier that I wrote, I return a subclass of JsonSerializer that wraps the argument JsonSerializer. This wrapper overrides only two methods:
serialize: only if certain conditions are met does it call serialize on the wrapped serializer
getDelegatee: returns the wrapped serializer
Questions:
should my wrapper extend some subclass of JsonSerializer instead of just JsonSerializer?
if so, should the subclass depend on the class of the wrapped serializer?
should my wrapper overload any other methods?
should my wrapper implement the same serializer modifier interfaces as the wrapped serializer? If so, then there are two problems:
I have to know every modifier interface, and update my BeanSerializerModifier to handle any new ones that are added to Jackson
I need to have a different wrapper class for each combination of modifier interfaces, which is very cumbersome
Good questions. Here are some thoughts:
Usually you should extend StdSerializer instead of "raw" JsonSerializer.
If serialization is as JSON Scalar value, you may want to extend StdScalarSerializer
Base type does not need to match, in general, although if delegating to Collection or Map serializers you may want to do that -- however, in general, you should need matching. It would get impractical soon as you correctly note.
On overloading: there are a few methods you may choose to overload, and usually just delegate to delegatee:
For polymorphic handling, define "serializeWithType(...)"
isEmpty(), if there are non-null values that correlate with concept of "empty": for example, String "" is considered empty.
acceptJsonFormatVisitor() is necessary to support JSON Schema generation and other type introspection (like generating Avro, CSV and Protobuf schemas, using matching data format modules)

Extending default Jackson deserialization

How can one obtain a default deserialized object in a custom Jackson deserializer?
I have an object which contains some fields which are not to be serialized, but which I wish to always be populated upon deserialization. In other words, a post-deserialize step.
I have created my own deserializer and annotated the class with a corresponding #JsonDeserialize, but I don't want to deserialize each field in the domain object by hand. Is there a way to get the regular deserialized object so I can just populate my custom fields? (Or else, just register a post-deserialization processor on a bean)
I have seen the answer to this question which hints at an answer, but I'm sufficiently unaware of the Jackson API to determine how best to actually effect this.
This can be achieved by using a BeanSerializerModifier and extending BeanSerializerBase, as per #ryanp's answer to this question.

What is difference between XmlSchemaType/XmlQualifiedName classes

Can someone tell me the difference between XmlSchemaType and XmlQualifiedName class. I'm bit confused when to choose which class. Actually I'm using IXmlSerializable interface for my class and to specify schema for this I used XmlSchemaProviderAttribute and specify the function which can return either XmlSchemaType or XmlQualifiedName. Both work fine and I successfully generate the proxy. but unable to find a consolidated analysis which one is to use in which condition.
As per Microsoft
XmlSchemaType Class:
The base class for all simple types and complex types.
XmlQualifiedName Class:
Represents an XML qualified name.
but I'm unable to understand the exact difference between these two.
After doing google and reading some article I've finally find the difference between these 2 and understand where to choose what?
There are 3 different types that can implement IXmlSerializable Interface
Content types
Element types
Legacy DataSet types
For content types we need to use XmlQualifiedName Class as return parameter (Method name specify in XmlSchemaProvider) and this will require that main root element of XSD will be the complextype.
For elements types we need to use XmlSchemaType Class. Here you can specify any root element in XSD.
For Legacy DataSet types we don't use XmlSchemaProvider attribute. Instead, they rely on GetSchema method for Schema generation.
I've found all this useful information from following MSDN link. A must read article for better understanding how Xml Serialization works in WCF.
Using the XmlSerializer Class

How do you fight growing parameter list in class hierarchy?

I have a strong feeling that I do not know what pattern or particular language technique use in this situation.
So, the question itself is how to manage the growing parameter list in class hierarchy in language that has OOP support? I mean if for root class in the hierarchy you have, let's say 3 or 4 parameters, then in it's derived class you need to call base constructor and pass additional parameters for derived part of the object, and so forth... Parameter lists become enormous even if you have depth of inheritance more than two.
I`m pretty sure that many of SOwers faced this problem. And I am interested in ways how to solve it. Many thanks in advance.
Constructors with long parameter lists is an indication that your class is trying to do too much. One approach to resolving that problem is to break it apart, and use a "coordinator" class to manage the pieces. Subclasses that have constructor parameter lists that differ significantly from their superclass is another example of a class doing too much. If a subclass truly is-a superclass, then it shouldn't require significantly more data to do its job.
That said, there are occasional cases where a class needs to work on a large number of related objects. In this situation, I would create a new object to hold the related parameters.
Alternatives:
Use setter injection instead of constructor injection
Encapsulate the parameters in a separate container class, and pass that between constructors instead.
Don't use constructors to initialize the whole object at once. Only have it initialize those things which (1) are absolutely required for the existence of the object and (2) which must be done immediately at its creation. This will dramatically reduce the number of parameters you have to pass (likely to zero).
For a typical hierarchy like SalariedEmployee >> Employee >> Person you will have getters and setters to retrieve and change the various properties of the object.
Seeing the code would help me suggest a solution..
However long parameter lists are a code-smell, so I'd take a careful look at the design which requires this. The suggested refactorings to counter this are
Introduce Parameter Object
Preserve Whole Object
However if you find that you absolutely need this and a long inheritance chain, consider using a hash / property bag like object as the sole parameter
public MyClass(PropertyBag configSettings)
{
// each class extracts properties it needs and applies them
m_Setting1 = configSettings["Setting1"];
}
Possibilities:
Perhaps your class(es) are doing too much if they require so much state to be provided up-front? Aim to adhere to the Single Responsibility Principle.
Perhaps some of these parameters should logically exist in a value object of their own that is itself passed in as a parameter?
For classes whose construction really is complex, consider using the builder or factory pattern to instantiate these objects in a readable way - unlike method names, constructor parameters lack the ability to self document.
Another tip: Keep your class hierarchy shallow and prefer composition to inheritence. That way your constructor parameter list will remain short.