#StackBounty: #java #json #jackson #jackson-databind Jackson multiple different schema for serialization of nested fields

Bounty: 50

I want to have several different schema when serializing with Jackson.
Suppose that I have the following classes:

public class Department {
      private Person head;
      private Person deputy;
      private List<Person> staff;
      // getters and setters
}

public class Person {
       private String name
       private int code;
      // getters and setters
}

Now, I want to have two different schema for Department class. The first one contains only head and deputy where head includes both name and code, but deputy has only name. The second schema should include all fields recursively.

Thus, we will have two different jsons. With the first schema:

{
    "head" : {
        "name" : "John",
        "code" : 123
     },
     "deputy" : { 
        "name" : "Jack"
     } 
}

, and with the second schema:

{
    "head" : {
        "name" : "John",
        "code" : 123
     },
     "deputy" : { 
        "name" : "Jack",
        "code" : "234"
     },
     "staff": [
        { 
            "name" : "Tom",
            "code" : "345"
         },
         { 
            "name" : "Matt",
            "code" : "456"
         },
     ]
}

QUESTION: How should I do it with Jackson?

NOTE: These classes are just examples. For this simple example, writing four different wrapper classes may be possible but think about a complex example with dozen of classes that each one has several fields. Using wrapper classes, we should generate a lot of boilerplate code.

Any help would be appreciated!


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.