0

I have a large nested object. I want to serialise this object in the JSON string, however I need only certain fields to be included. Problem here is that fields could change very frequently and I want to build it in a way that could help me easy include or exclude fields for serialisation.

I know that I can write a lot of code to extract certain fields and build JSON "manually". But I wonder if there are any other elegant way to achieve similar outcome but specifying a list of required fields?

For example having following object structure I want include only id and name in the response:

class Building {
    private List<Flat> flats;
}

class Flat {
    private Integer id;     
    private Person owner;
}


class Person {
    private String name;
    private String surname;
}

Json:

{
    "flats" : [
        {
            "flat":
            {
                "id" : "1",
                "person" : {
                    "name" : "John"
                }
            }
        }
    ]
}
Wild Goat
  • 3,509
  • 12
  • 46
  • 87

3 Answers3

2

You can use gson for serializing/deserializing JSON. Then you can include the @Expose annotation to use only the fields you require.

Be sure to also configure your Gson object to only serialize "exposed" fields.

Gson gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

Alternative:

You can actually do it the inverse way, marking fields which will not be exposed. You can do this with the transient keyword. So whatever you want to ignore just add transient to it. Here's how it works on gson.

PS: This works on most Java JSON serializers too.

Gent Ahmeti
  • 1,559
  • 13
  • 17
  • Sounds great, I will try that! In case I mark entire private Person owner field as @Expose will it automatically include all nested fields as well? – Wild Goat Oct 06 '17 at 10:57
  • Actually you have to mark all fields with the `@Expose` annotation if you want them serialized. I edited the answer with an alternative, read that too, maybe that is better suited for you. – Gent Ahmeti Oct 06 '17 at 11:09
0

Using com.fasterxml.jackson.annotation.JsonIgnore is another way to achieve this.

import com.fasterxml.jackson.annotation.JsonIgnore;

class Person {
    private String name;
    @JsonIgnore
    private String surname;
}

It will ignore the surname when the parser converts the bean to json. Similar annotation will be available in other json processing libraries.

Kajal
  • 709
  • 8
  • 27
0

If using Gson, study how to use ExclusionStrategy & JsonSerializer.

Using those is a more flexible way to control serialization since it allows to decide per serialization what to serialize.

Using annotations requires later to add / remove those annotations from fields if there is a need to change what to serialize.

In the case of your example the latter might be more appropriate.

This question might be good startpoint serialize-java-object-with-gson

pirho
  • 11,565
  • 12
  • 43
  • 70