我有这样的回应:
[ { "key": { "kind": "UserRecord", "id": 0, "name": "1" }, "firstName": "1", "lastName": "1", "homeLat": 0.0, "homeLon": 0.0, "workLat": 0.0, "workLon": 0.0, "currentLat": 10.0, "currentLon": 10.82, "timestamp": 1335735046606, "score": 0, "isStarred": false, "distance": 0.0 }, { "key": { "kind": "UserRecord", "id": 0, "name": "32423542324234324" }, "firstName": "Simone", "lastName": "Boscolo Berto", "homeLat": 0.0, "homeLon": 0.0, "workLat": 0.0, "workLon": 0.0, "currentLat": 55.786444, "currentLon": 12.515867, "timestamp": 1335884083696, "score": 0, "isStarred": false, "distance": 0.0 } ]
以及每个JSONObject给我我的对象的方法
private User getUserFromJson(JSONObject jsonUser)
如何在该JSONObjects列表中进行迭代?我应该使用JSONArrayobject吗?
解决方法:
使用Gson或jackson可能很容易
格森的例子
Gson gson = new Gson();
User[] users = gson.fromJson(, User[].class);
杰克逊的例子
ObjectMapper mapper = new ObjectMapper();
Collection users =
mapper.readValue(, `new TypeReference>() {});
样品-
package com.test;
import com.google.gson.Gson;
public class GSonExample {
public static void main(String[] args) {
String json = "{\"name\":\"Duke\",\"address\":\"Menlo Park\",\"dateOfBirth\":\"Feb 1, 2000 12:00:00 AM\"}";
Gson gson = new Gson();
User student = gson.fromJson(json, User.class);
System.out.println("student.getName() = " + student.getName());
System.out.println("student.getAddress() = " + student.getAddress());
System.out.println("student.getDateOfBirth() = " + student.getDateOfBirth());
}
}
public class User {
private String name;
private String address;
private String dateOfBirth;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
类路径
标签:java,arrays,json
来源: https://codeday.me/bug/20191012/1897766.html