0

I'd like to deserialize this using GSON into a list of Post, but can't figure out how to tell GSON how to ignore the root element "posts" (as its an object) and just process the array.

I've got:

Type postTypeList = new TypeToken<List<Post>>(){}.getType();

JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(myJSONString);
JsonObject postsRootObj = jsonElement.getAsJsonObject();

List<Post> postList = gson.fromJson(postsRootObj.get("posts"), postTypeList);

BUT.. I'd rather not have the whole JsonParser, I'd rather just pass it directly into the gson.fromJson function.. Is there a way to do this?

{ "posts":
  [      

        {
       "username": "John",  
       "message": "I'm back",
       "time": "2010-5-6 7:00:34"
        "validator":[{
                        "prog": "Name1",
                        "name": "Name2",
                        "computername": "Name3",
                        "date": "2010-11-20 19:39:55"
                      }]
        }
      ,

        {
          "username": "Smith",
          "message": "I've been waiting",
          "time": "2010-4-6 10:30:26"
           "validator":[{
                        "prog": "Name1",
                        "name": "Name2",
                        "computername": "Name3",
                        "date": "2010-11-20 19:39:55"
                      }]

       }
]}

2 Answers 2

1

Create a wrapper class which will have List<Post> as its member

public class PostList{
private List<Post> posts;
// getter and setters for posts
}

And then use fromJson in the similar fashion

List<Post> postList = gson.fromJson(myJSONString,PostList.class);
Sign up to request clarification or add additional context in comments.

2 Comments

This is the other approach I thought of, however in my opinion its an unnecessary class, I was just hoping something might have been built into GSON to assist with my problem.
Ohh okay! Hmmm..I could only think of this and the approach you wrote..Correct me if I'm wrong,but I don't think there will be any way to force Gson to completely ignore the root element..
0

There is a correction from above. Usage should be :

 PostList postList = gson.fromJson(myJSONString,PostList.class);
 Post post = postlist.get(index) //index is the index of list you want to access

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.