将 JSONObjects 转换为 ArrayList



我想将我的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) {
}
});

您可以使用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));
}

如果你使用 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());
}

无需显式转换为列表,fastjson 为您完成。

最新更新