我想将我的JsonObject转换为纬度和经度的ArrayList。三天我一直在努力解决这个问题而没有任何结果。请帮忙!
这是我的JSON:
{
"hits":[
{
"_geoloc":{
"lat":33.842624,
"lng":-5.480229
},
"objectID":"-KsPQUlvJK-PCSrH3Dq3"
},
{
"_geoloc":{
"lat":33.84878,
"lng":-5.481698
},
"objectID":"-KsPQUloi4BAduevPJta"
}
],
"nbHits":2,
"page":0,
"nbPages":1,
"hitsPerPage":20,
"processingTimeMS":1,
"exhaustiveNbHits":true,
"query":"",
"params":"aroundLatLng=33.62727138006218%2C-4.498191252350807&aroundRadius=545000"
}
这是我的代码:
client.getIndex("users").searchAsync(query, new CompletionHandler() {
@Override
public void requestCompleted(JSONObject jsonObject, AlgoliaException e) {
}
});
答案 0 :(得分:0)
您可以使用JsonObject的成员方法执行此操作(http://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html)。例如,类似以下内容:
class GeoPoint {
private double lat;
private double lon;
public GeoPoint( double lat, double lon ) {
this.lat = lat
this.lon = lon
}
// ...
}
ArrayList<GeoPoint> list = new ArrayList<>();
// Thankfully JsonArray objects are iterable...
for (JsonValue e : jsonObject.getJsonArray("hits")) {
JsonObject coordWrapper = (JsonObject) e;
JsonObject coord = coordWrapper.getJsonObject("_geoloc");
double lat = coord.getJsonNumber("lat").doubleValue();
double lon = coord.getJsonNumber("lon").doubleValue();
list.add(new GeoPoint(lat, lon));
}
答案 1 :(得分:0)
如果您使用fastjson作为JSON库,可以这样做:
public class GeoLoc {
private double lng;
private double lat;
// getter & setter...
}
public class Geo {
private String objectID;
@JSONField(name = "_geoloc")
private GeoLoc geoLoc;
// getter & setter...
}
public static void main(String[] args) {
String jsonStr = ""; // Your json string here.
JSONObject jsonObject = JSON.parseObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("hits");
List<Geo> geos = jsonArray.toJavaList(Geo.class);
List<GeoLoc> geoLocs = geos.stream()
.map(Geo::getGeoLoc)
.collect(Collectors.toList());
}
不需要显式转换为List,fastjson会为你做这件事。