简体   繁体   中英

Object serialization to json, certain fields only

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"
                }
            }
        }
    ]
}

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM