-1

I am a bit lost here,

I have a JSON string like this:

{  
"type":"fuu",
"message":"bar",
"data":{  
  "5":{  
     "post":"foo",
     "type":"bar",

  },
  "0":{  
     "post":"foo",
     "type":"bar",

  },
  "1":{ 
     "post":"foo",
     "type":"bar",

   },

  // and so on...

 }
}

Please how do I parse it into POJOs using Gson? (I need to get the list of objects)

I am a bit confused by the number in front of the elements of the list of objects....

user229044
  • 232,980
  • 40
  • 330
  • 338
Lisa Anne
  • 4,482
  • 17
  • 83
  • 157

2 Answers2

2

Try this -

Pojo.java

import java.util.Map;

public class Pojo {
    private String type;
    private String message;
    private Map<Integer, InnerPojo> data;
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public Map<Integer, InnerPojo> getData() {
        return data;
    }
    public void setData(Map<Integer, InnerPojo> data) {
        this.data = data;
    }
    @Override
    public String toString() {
        return "Pojo [type=" + type + ", message=" + message + ", data=" + data
                + "]";
    }
}

InnerPojo.java

public class InnerPojo {
    private String type;
    private String post;
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getPost() {
        return post;
    }
    public void setPost(String post) {
        this.post = post;
    }
    @Override
    public String toString() {
        return "InnerPojo [type=" + type + ", post=" + post + "]";
    }
}

Main.java

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.testgson.beans.Pojo;

public class Main {
    private static Gson gson;

    static {
        gson = new GsonBuilder().create();
    }

    public static void main(String[] args) {
        String j = "{\"type\": \"fuu\", \"message\": \"bar\", \"data\":{ \"0\":{\"post\": \"foo\", \"type\": \"bar\"}, \"1\":{\"post\": \"foo\", \"type\": \"bar\"}, \"5\":{\"post\": \"foo\", \"type\": \"bar\"}}}";
        Pojo p = gson.fromJson(j, Pojo.class);
        System.out.println(p);
    }
}

And Result is -

Pojo [type=fuu, message=bar, data={0=InnerPojo [type=bar, post=foo], 1=InnerPojo [type=bar, post=foo], 5=InnerPojo [type=bar, post=foo]}]
Saurabh
  • 2,384
  • 6
  • 37
  • 52
0

For the "data" part, I'd try to parse it into a Map<Integer, TypedPost> structure, see this thread for instructions.

Community
  • 1
  • 1
Binkan Salaryman
  • 3,008
  • 1
  • 17
  • 29