把这个json解析为java

时间:2016-01-05 12:03:06

标签: java json parsing gson

我以下列形式hava json:

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

和Java类 - >

public class UserResponses {
    private Integer question;

    private String answer;
//getters and setters
}

如何将json解析为UserResponses列表? 例如,使用GSON?

2 个答案:

答案 0 :(得分: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);
          }

这是使用gson解析数据的简单方法。如果你想在没有gson的情况下这样做,你只需要使用questionArray.getJSONObject(i).getString("question")questionArray.getJSONObject(i).getString("answer")的UserResponse类的getter和setter。

答案 1 :(得分:0)

  

如何将json解析为UserResponses列表?例如,使用GSON?

鉴于包含json的“json”变量rappresenting your_kind列表,我将按照以下方式执行(使用反射):

Type type = new TypeToken&gt;(){}。getType();

列出yourList = Gson()。fromJSON(json,type);