我想对阵列使用GSON.
我看了一些示例,但无法使其与我的代码一起使用.
Using GSON to parse a JSON array.
我收到此错误消息:预期为字符串,但在行1列为BEGIN_ARRAY
在该项目中,我遵循的原始教程涉及解析Json Objects.
我的杰森:
[{
"nid": "25",
"title": "angry guy",
"body": "fhjk gjj"
}, {
"nid": "24",
"title": "25 mobile",
"body": "25 test tes"
}, {
"nid": "8",
"title": "new post 4",
"body": "sdfsdf sdfsdf"
}, {
"nid": "7",
"title": "new post",
"body": "sdf sdf sdfsdf"
}]
我的代码:
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<ExerciseModel> exerciseModelList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
ExerciseModel exerciseModel = gson.fromJson(finalObject.toString(), ExerciseModel.class);
exerciseModelList.add(exerciseModel);
}
return exerciseModelList;
我的模特:
public class ExerciseModel {
private int nid;
private String title;
private String body;
public int getNid() {
return nid;
}
public void setNid(int nid) {
this.nid = nid;
}
public String getTitle() {
return title;
}
public String toString() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
提前致谢
解决方法:
你的课应该是
public class ExerciseModel
{
private String nid;
public String getNid() { return this.nid; }
public void setNid(String nid) { this.nid = nid; }
private String title;
public String getTitle() { return this.title; }
public void setTitle(String title) { this.title = title; }
private String body;
public String getBody() { return this.body; }
public void setBody(String body) { this.body = body; }
}
GSON代码的代码应为:
String json = "[{ \"nid\": \"25\", \"title\": \"angry guy\", \"body\": \"fhjk gjj\" }, { \"nid\": \"24\", \"title\": \"25 mobile\", \"body\": \"25 test tes\" }, { \"nid\": \"8\", \"title\": \"new post 4\", \"body\": \"sdfsdf sdfsdf\" }, { \"nid\": \"7\", \"title\": \"new post\", \"body\": \"sdf sdf sdfsdf\" }]";
Type listOfTestObject = new TypeToken<List<ExerciseModel>>() {}.getType();
ArrayList<ExerciseModel> models = new Gson().fromJson(json, listOfTestObject);
System.out.println(models.get(0).getTitle());