0

I have the following json string:

[
    {
        "question" : {
            "questionId" : 1109,
            "courseId" : 419
        },
        "tags" : ["PPAP", "testtest"],
        "choices" : [{
                "choiceId" : 0,
                "questionId" : 0
            }, {
                "choiceId" : 0,
                "questionId" : 0
            }
        ]
    }
]

How do I make question, tags, and choices into separate objects using GSON? Currently I only use fromJson and can only convert a JSON string if it only contains 1 type of object.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
ryuuuuuusei
  • 98
  • 5
  • 22
  • One type of object can internally contain fields which hold instances of other types. So You need class which internally contains `question` field of type which internally has `questionId` and `courseId` field. You can generate such classes via http://www.jsonschema2pojo.org/. Then deserialize your json string to array or list of such classes. – Pshemo Oct 19 '16 at 09:38

2 Answers2

0

You can have following classes

class Question{
   questionId; //specify data type 
   courseId;
}
class Choice{
   choiceId;
   questionId;
}

Then you can define one more class which will hold all the three member variables

class Extract{
 Question question;
 List<String> tags;
 List<Choice> choices;
} 

Then you can pass this Extract class to fromJson method like

List<Extract> result = gson.fromJson(jsonString, new TypeToken<List<Extract>>(){}.getType());
0

This worked for me with the POJO classes defined.

public static void main(String[] args) {
String jsonString = "[{\"question\":{\"questionId\":1109,\"courseId\":419},\"tags\":[\"PPAP\",\"testtest\"],\"choices\":[{\"choiceId\":0,\"questionId\":0},{\"choiceId\":0,\"questionId\":0}]}]";
        Gson gson = new Gson();

        JsonParser parser = new JsonParser();
        JsonArray array = parser.parse(jsonString).getAsJsonArray();

        for (final JsonElement json : array) {
            JsonModel jsonModel = gson.fromJson(json, new TypeToken<JsonModel>() {
            }.getType());
            System.out.println(jsonModel.toString());
        }

}
public class JsonModel implements Serializable {

    private static final long serialVersionUID = -2255013835370141266L;
    private List<Choices> choices;
    private List<String> tags;
    private Question question;
    ...    
    getters and setters
  }

public class Choices implements Serializable{

    private static final long serialVersionUID = 3947337014862847527L;

    private Integer choiceId;
    private Integer questionId;
    ...    
    getters and setters
}

public class Question implements Serializable{

    private static final long serialVersionUID = -8649775972572186614L;

    private Integer questionId;
    private Integer courseId;
    ...    
    getters and setters
}
notionquest
  • 37,595
  • 6
  • 111
  • 105