-1

I hava json in the following form:

"result":[
   {"question":"3", "answer":"Doe"},
   {"question":"5", "answer":"Smith"},
   {"question":"8","answer":"Jones"}
]

and a Java class ->

public class UserResponses {
    private Integer question;

    private String answer;
//getters and setters
}

How can i parse the json into a List of UserResponses? For example, with GSON?

rurounisuikoden
  • 269
  • 1
  • 4
  • 16
  • question <-> position ? What have you tried so far? Googling "simple gson example" should get you started. – Jan Jan 05 '16 at 12:04
  • 1
    Check the answer given to you on http://stackoverflow.com/questions/31777282/how-to-deal-with-json-string-in-java-servlet - you should still have code? – Jan Jan 05 '16 at 12:05
  • 1
    Possible duplicate of [JSON parsing using Gson for java](http://stackoverflow.com/questions/5490789/json-parsing-using-gson-for-java) – Dhia Jan 05 '16 at 12:15

2 Answers2

0
JSONObject data = new JSONObject("your_json_data_here");
    JSONArray questionArray = data.getJSONArray("result");
    //Create an array of questions to store the data
    UserResponse[] responsess = new UserResponse[questionArray.length()];
    //Step through the array of JSONObjects and convert them to your Java class
    Gson gson = new Gson();
    for(int i = 0; i < questionArray.length(); i++){
         responses[i] = gson.fromJson(
              questionArray.getJSONObject(i).toString(), UserResponse.class);
          }

This would be a simple way to parse the data with gson. If you wanted to do it without gson you would just have to use the getters and setters for your UserResponse class with questionArray.getJSONObject(i).getString("question") and questionArray.getJSONObject(i).getString("answer").

Joopkins
  • 1,606
  • 10
  • 16
0

How can I parse the json into a List of UserResponses? For example, with GSON?

Given the "json" variable containing the json rappresenting a list of your_kind I would do as following (using reflection):

Type type = new TypeToken>() {}.getType();

List yourList = Gson().fromJSON(json, type);

Simone Salvo
  • 343
  • 1
  • 2
  • 11