Ok so I edited the question because it wasn’t clear enough.
Edit 2 : updated the JSON file.
I’m using GSON in an Android app, and I need to parse JSON files, that come from a server, and are a little too complexes. I don’t want to have my object structure too heavy, so I would like to simplify the contents : so the structure of my object won’t be the structure of the JSON file.
For example, if in the JSON I have this :
{
"object1":{
"attribute1" : "test1",
"attribute40" : "test40",
"user":{
"id":1,
"name":"foo"
}
,"example":{
"total":10,
"list":[
{
"tag":"tag1",
"name":"object name 1",
"pos":1
},
{
"tag":"tag10",
"name":"object name 10",
"pos":10
}
]
}
}
"object2":{
"attribute1":"test..."
}
}
I don’t want to keep in my current object structure, an object Example, that contains an ArrayList and an int “total”. But I would like to keep only a simple String with the value "object name 1;object name 2;...".
Moreover, I would like to store only the user Id, not the complete User, because I already have the complete user stored somewhere else, with an other server API call.
So my class class would be something like :
class Foo{
int userId;
String example; //"object name 1;object name 2;..."
...
}
So I suppose that we can achieve this with a custom deserializer, but I don’t find how. I would like if possible to minimize the memory, so I don’t think that having a full object example, and then use it to build my String example is a correct way.
In the worst case, if it’s too complicated, I would like to be able to store at least only the list of Tag items when I parse the Example Object : so I need a custom deserializer to get rid off the int total.
So I would have :
class Foo{
int userId;
ArrayList<Tag> example;
...
}
I adopted the answer to present the full solution designed in chat and to fit to the changed JSON string. The code assumes that the string json holds exactly the (updated) JSON from the question. The requirement is to fill the following class (setter and toString ommitted):
GSON supports (as the most other REST-libs) three modes:
Reads the whole JSON via
JsonParser.parse()and builds a DOM tree in memory (object model access). Therefore this solution is good for small JSON files.Reads only chunks of the JSON via
JsonReader. Code is more complicated, but it is suited for large JSON files. As of Android 3.0 Honeycomb, GSON’s streaming parser is included asandroid.util.JsonReader.Databinding directly to classes via reflection, minimizes the code significantely. GSON allows mixed mode, which means to combine GSON_DOM and GSON_BIND or GSON_STREAM and GSON_BIND which this answer should show.
To fill the class Object1 via GSON_DOM and GSON_BIND the implementation looks like:
To fill the class Object1 via GSON_STREAM and GSON_BIND the implementation looks like: