我有一个嵌套的JSON,如下所示。我想提取密钥,例如PersonB
基于对其价值的搜索,例如Age ==60
。 JSON是正确的数据结构来实现这样的东西吗?我尝试过使用JSONpath。但无法提出一个查询来提取这样的东西。
{
"PersonA":{
"shortnames":[
"Bravo",
"Delta"
],
"Name":"Person 123",
"Age":"15",
"Maritial Status":"Single",
"Work Experience":"O",
"ID":291
} "PersonB":{
"shortnames":[
"Alpha",
"Tango"
],
"Name":"Person 234",
"Age":"60",
"Maritial Status":"Married",
"Work Exxperience":"2O",
"ID":292
}
}
关于这样的查询看起来如何的任何指针?
答案 0 :(得分:0)
以下是获取年龄为'60'的密钥的示例代码。
public static void main(String[] args) {
String jsonString = "{\"PersonA\": {\"shortnames\": [\"Bravo\",\"Delta\"],\"Name\": \"Person 123\",\"Age\": \"15\",\"Maritial Status\": \"Single\",\"Work Experience\": \"O\",\"ID\": 291},\"PersonB\": {\"shortnames\": [\"Alpha\",\"Tango\"],\"Name\": \"Person 234\",\"Age\": \"60\",\"Maritial Status\": \"Married\",\"Work Exxperience\": \"2O\",\"ID\": 292},\"PersonC\": {\"shortnames\": [\"Alpha\",\"Tango\"],\"Name\": \"Person 234\",\"Maritial Status\": \"Married\",\"Work Exxperience\": \"2O\",\"ID\": 292}}";
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
for (Entry<String, JsonElement> jsonEntry : jsonObject.entrySet()) {
if (jsonEntry.getValue().getAsJsonObject().get("Age") != null ) {
if (jsonEntry.getValue().getAsJsonObject().get("Age").getAsString().equals("60")) {
System.out.println(jsonEntry.getKey());
System.out.println(jsonEntry.getValue());
}
}
}
}
<强>输出: - 强>
PersonB
{"shortnames":["Alpha","Tango"],"Name":"Person 234","Age":"60","Maritial Status":"Married","Work Exxperience":"2O","ID":292}