我有一堆字符串符号的JSON对象:
"{\"address\":{\"street\":\"Steenstraat\",\"housenumber\":\"17A\",\"postalcode\":\"6828 CA\",\"city\":\"ARNHEM\",\"geoLocation\":{\"lat\":\"51.983718\",\"lng\":\"5.915553\"}},\"distance\":0,\"type\":\"ING\"}
所以每个JSON对象看起来都是这样的:
{
"address" : {
"street" : "Steenstraat",
"housnumber" : "17A",
"postalcode" : "6828 CA",
"city" : "ARNHEM",
"geolocation" : {
"latitude" : "51.983718",
"longitude" : "54.983718"
}
},
"type" : "citi",
"distance" : 0
}
现在,我使用谷歌的gson库来获取其余的API,这给了我一串上述许多JSON对象。我如何尝试过滤掉(或重新定义JSON的结构)以按特定参数对JSON对象进行排序(比如按城市名称排序)?
这是我的Atm课程。我正在尝试将JSON字符串转换为Atm对象列表。
public class Atm {
private String type;
private Long distance;
private Map<String, String> address = new HashMap<String, String>();
public Atm() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Long getDistance() {
return distance;
}
public void setDistance(Long distance) {
this.distance = distance;
}
public Map<String, String> getAddress() {
return address;
}
public void setAddress(Map<String, String> address) {
this.address = address;
}
@Override
public String toString() {
return "Atm{" +
"type='" + type +
", distance=" + distance +
", address=" + address.toString() +
'}';
}
}
或者有没有办法在不将其转换为java数据结构的情况下执行此操作?
答案 0 :(得分:0)
注意:当您在JSON中使用子元素geoLocation
时,您无法使用Map<String, String>
。
您应该使用:Map<String, Object>
代替或创建自定义类来表示您的地址。
要按城市过滤Atm
列表,您可以执行以下操作。
在Java 8中:
Gson gson = new Gson();
String atm1 = "{\"address\":{\"street\":\"Steenstraat\",\"housenumber\":\"17A\",\"postalcode\":\"6828 CA\",\"city\":\"ARNHEM\",\"geoLocation\":{\"lat\":\"51.983718\",\"lng\":\"5.915553\"}},\"distance\":0,\"type\":\"ING\"}";
String atm2 = "{\"address\":{\"street\":\"Steenstraat\",\"housenumber\":\"17A\",\"postalcode\":\"6828 CA\",\"city\":\"ARNHEM\",\"geoLocation\":{\"lat\":\"51.983718\",\"lng\":\"5.915553\"}},\"distance\":0,\"type\":\"ING\"}";
String atm3 = "{\"address\":{\"street\":\"Steenstraat\",\"housenumber\":\"17A\",\"postalcode\":\"6828 CA\",\"city\":\"NEW-YORK\",\"geoLocation\":{\"lat\":\"51.983718\",\"lng\":\"5.915553\"}},\"distance\":0,\"type\":\"ING\"}";
List<Atm> atms = new ArrayList<Atm>();
atms.add(gson.fromJson(atm1, Atm.class));
atms.add(gson.fromJson(atm2, Atm.class));
atms.add(gson.fromJson(atm3, Atm.class));
List<Atm> filteredOnCity = atms.stream().filter(atm -> atm.getAddress().get("city")
.equals("ARNHEM")).collect(Collectors.toList());
使用Apache commons-collections4:
//Build your list with code from above
Predicate<Atm> filterOnCity = new Predicate<Atm>() {
@Override
public boolean evaluate(Atm atm) {
return atm.getAddress().get("city").equals("ARNHEM");
}
};
CollectionUtils.filter(atms, filterOnCity);
答案 1 :(得分:0)
为什么不在将它们发送到Java之前在客户端进行过滤或排序?
var arr = JSON.parse(MY_JSON_ARRAY_STRING);
arr.sort(function(a, b){
if ( a.city < b.city )
return -1;
if ( a.city > b.city )
return 1;
return 0;
});
var arrString = JSON.stringify(arr);