-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?

3
  • question <-> position ? What have you tried so far? Googling "simple gson example" should get you started. Commented Jan 5, 2016 at 12:04
  • 1
    Check the answer given to you on stackoverflow.com/questions/31777282/… - you should still have code? Commented Jan 5, 2016 at 12:05
  • 1
    Possible duplicate of JSON parsing using Gson for java Commented Jan 5, 2016 at 12:15

2 Answers 2

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").

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.