将此json解析为java
我有以下格式的json:将此json解析为java,java,json,parsing,gson,Java,Json,Parsing,Gson,我有以下格式的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 an
"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?JSONObject data=newjsonobject(“这里是您的json数据”);
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);
}
JSONArray questionArray=data.getJSONArray(“结果”);
//创建一系列问题来存储数据
UserResponse[]responsess=newuserresponse[questionArray.length()];
//逐步遍历JSONObject数组并将其转换为Java类
Gson Gson=新的Gson();
对于(int i=0;i
这将是一种使用gson解析数据的简单方法。如果您想在没有gson的情况下执行此操作,您只需将UserResponse类的getter和setter与questionArray.getJSONObject(i).getString(“问题”)
和questionArray.getJSONObject(i).getString(“答案”)
一起使用即可
如何将json解析为用户响应列表?例如,使用GSON
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);
}
给定包含json参数的“json”变量,并给出您的类型列表,我将执行以下操作(使用反射):
Type Type=newTypeToken>(){}.getType()
List yourList=Gson().fromJSON(json,类型) 问题立场?到目前为止你试过什么?谷歌搜索“简单gson示例”应该可以让你开始了。检查上给你的答案-你应该还有代码?可能是重复的