【问题标题】:Parse this json to java将此json解析为java
【发布时间】:2016-01-05 12:03:06
【问题描述】:

我有以下格式的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 解析为用户响应列表? 例如,使用 GSON?

【问题讨论】:

标签: java json parsing gson


【解决方案1】:
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。

【讨论】:

    【解决方案2】:

    如何将 json 解析为用户响应列表?例如,使用 GSON?

    鉴于“json”变量包含 json rappresenting your_kind 列表,我将执行以下操作(使用反射):

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

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

    【讨论】:

      猜你喜欢
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多