Omit specific JSON properties from analysis when using GSON

I am using Google GSON. I have a JSON data file, for example:

{"NAME":"Joe",
"AGE":"18",
"DATA":[0,0,0,0,0,...]}

Where DATAis a very, very large array.

I would like to read the JSON file, but skip certain properties from the analysis. In the above case, I would like to skip reading DATAand therefore get JsonObjectone that contains only NAMEand AGE.

I have tens of thousands of these files, and I need to read the fields NAMEand AGEeach of them. It’s so clear that I don’t need to parse DATAwhat I consider a huge waste of resources, given the number of files I need to process.

Can this be done using Google GSON?

+4
source share
1 answer

Yes it is possible. GSON supports annotations.

Create a simple POJO if you don't already have one.

public class Person {
    @Expose @SerializedName("NAME")
    public String name;
    @Expose @SerializedName("AGE")
    public String age; // because your snippet showed "18" in quotes

    // getters and setters, if you like
}

You must edit your class and use annotations correctly @Expose.

When you instantiate an object Gsonto convert JSON to an object Person, use this:

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

This way, Gson will know which fields to look for and which to ignore.

EDIT: The attributes in Personare publicbecause I assume that you will not use getters and setters.

+2
source

All Articles