我希望搜索一个给定值的JsonArrays的ArrayList。下面是我的ArrayList valueList
中包含的数据示例:
[
[
{
"blobJson": "x",
"deviceMfg": 10,
"eventCode": 0,
"sensorClass": 3,
"sensorUUID": "15633094",
"timeStamp": 1485433626.504731,
"uID": "15633094_3_10"
},
{
"blobJson": "x",
"deviceMfg": 10,
"eventCode": 0,
"sensorClass": 3,
"sensorUUID": "19458142",
"timeStamp": 1483916820.538747,
"uID": "19458142_3_10"
},
{
"blobJson": "x",
"deviceMfg": 10,
"eventCode": 1,
"sensorClass": 3,
"sensorUUID": "22808642",
"timeStamp": 1485937952.330456,
"uID": "22808642_3_10"
}
]
]
我希望在valueList
中搜索timeStamp
字段的值并提取它,我该怎么做?
(我正在使用GSON库来解析JSON)
答案 0 :(得分:0)
如果您可以使用Java 8,则可以使用Streams API来提取时间戳:
private static final TypeToken<List<List<JsonObject>>> listOfListOfJsonObjectsTypeToken = new TypeToken<List<List<JsonObject>>>() {
};
final List<List<JsonObject>> arrays = gson.fromJson(JSON, listOfListOfJsonObjectsTypeToken.getType());
final List<Double> timestamps = arrays.stream()
.flatMap(Collection::stream)
.map(jo -> jo.get("timeStamp"))
.map(JsonElement::getAsJsonPrimitive)
.map(JsonPrimitive::getAsDouble)
.collect(toList());
System.out.println(timestamps);
给出:
[1.485433626504731E9,1.483916820538747E9,1.485937952330456E9]
修改强>
您可能还想使用旨在查询JSON对象的JsonPath之类的JSON查询库:
final DocumentContext context = JsonPath.parse(JSON);
final JSONArray timestampsJsonArray = context.read(JsonPath.compile("$[0][*].timeStamp"));
final List<Double> timestamps = timestampsJsonArray.stream()
.map(o -> (Number) o)
.map(Number::doubleValue)
.collect(toList());
System.out.println(timestamps);
会产生完全相同的结果。
修改2
如果没有假设JSON解析/处理,您可以使用:
final List<Double> timeStamps = valueList.stream()
.flatMap(ja -> StreamSupport.stream(ja.spliterator(), false))
.map(JsonElement::getAsJsonObject)
.map(jo -> jo.get("timeStamp"))
.map(JsonElement::getAsJsonPrimitive)
.map(JsonPrimitive::getAsDouble)
.collect(toList());
System.out.println(timeStamps);
结果相同。