Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize class with generic to JSON using Jackson

I have a structure of objects representing a Questionnaire and I need to serialize to JSON. One class of the structure is a OpenQuestion and this class use generics with two parameters. The problem starts when one of types used was Date, the date is serialized wrong, like a long.

Class code:

public class OpenQuestion <valueType,validationType> extends AbstractQuestion implements    Serializable {
    private valueType value;
    private validationType minValue;
    private validationType maxValue;
    ...
}

I saw how to serialize a date in a hash map if the hash map always uses a Date, but in this case I use the class with String, Integer or Date.

Any idea to solve it? Thanks

like image 689
James2707 Avatar asked Oct 21 '25 08:10

James2707


1 Answers

You can add a JsonTypeInfo annotation for this. There's two ways of using this:

  • Get it to automatically add a type annotation to your object, so it knows what to deserialize it as.
  • Add a custom type resolver, to handle this for you.

The first will make your JSON ugly, but requires very little extra code and doesn't force you to make custom serializers. The latter is more difficult, but will result in cleaner JSON. Overall the problem is partly that one of your types isn't modelled in JSON (Date) so you'll probably need it to be serialised as an integer or String type in your JSON file.

The former option looks a bit like this:

@JsonTypeInfo( use = Id.CLASS, include = As.WRAPPER_PROPERTY )
private valiationType minValue;

This should encode say, a String value, as something like:

{ __type = "java.lang.String", value = "Hello, World" }

No promises on that being accurate as this is mostly from memory!

like image 105
Calum Avatar answered Oct 22 '25 22:10

Calum