Default deserialization of POJO containing another POJO with custom deserialization

33 views
Skip to first unread message

Oleksandr Khamylov

unread,
Aug 16, 2014, 10:38:05 AM8/16/14
to jackso...@googlegroups.com

Hi there.

Can't find out how to handle the next situation..

For instance, I have two classes:


public class ClassA {
 
    private String a;
    private int b;
    private Pair p;
 
    // constructors, getters and setters
}


public class Pair {
 
    private String x;
    private String y;
 
    // constructors, getters and setters
}


And I want serialized JSON to look smth. Like this:

"classA" :{
    "a" : "value a",
    "b" : 123,
    "p" : "44=>77"
}


So, I want Pair to be serialized/deserialized to/from a string with a specified pattern (e.g., <x>=><y>)


Cant' get it working specifying only custom JsonSerializer/JsonDeserializer for Pair class.

Does anyone have an ideas about solution?

Tatu Saloranta

unread,
Aug 16, 2014, 5:09:32 PM8/16/14
to jackso...@googlegroups.com
Yes, custom serialization/deserialization is the way to go.

But instead of external JsonSerializer/JsonDeserializer, it may be possible to modify Pair class (if you have access) to:

1. For serialization, two main options:
    (a) Specify method to produce serialization as String, like so:
       @JsonValue
       public String asJson() { return String.format(....); }
    (b) Make Pair implement JsonSerializable
2. For deserialization, you can add "delegating creator", which gets JSON String; either factory method or constructor, so like:
    @JsonCreator
    public Pair(String jsonValue) {
           ...
    }

    OR

     @JsonCreator
     public static Pair factoryMethod(String jsonValue) { .... }

Hope this helps,

-+ Tatu +-



--
You received this message because you are subscribed to the Google Groups "jackson-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jackson-user...@googlegroups.com.
To post to this group, send email to jackso...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages