我有一个程序,可以搜索 JSON 对象以匹配值,当它匹配某个值时,我希望它返回对象名称以及与匹配值关联的键。
这是我当前拥有的代码,它根据需要匹配值并返回对象名称,我需要它返回具有匹配值的关联键(我正在使用 GSON 库)。
testHarnessSensor
是要匹配的值,例如椅子
ArrayList<String> currentActivity = new ArrayList<String>();
int i=0;
try {
InputStream input = getClass().getResourceAsStream("/drink.json");
JsonReader jsonReader = new JsonReader(new InputStreamReader(input));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String nameRoot = jsonReader.nextName();
if (nameRoot.equals("Activities")) {
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String activityName = jsonReader.nextName();
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String n = jsonReader.nextName();
n = jsonReader.nextString();
if (testHarnessSensor.equals(n)) {
currentActivity.add(activityName);
}
}
jsonReader.endObject();
}
jsonReader.endObject();
}
}
jsonReader.endObject();
jsonReader.close();
}
catch (Exception e) {
System.out.println(e);
}
根据请求的 JSON 文件:
{
"Activities": {
"Cold Drink": {
"required": "kitchenDoor",
"optional": "cup",
"optional": "fridge",
"required": "juice"
},
"Hot Drink": {
"required": "kitchenDoor",
"required": "cup",
"required": "water",
"required": "kettle",
"optional": "sugar",
"required": "microwave",
"required": "tea/coffee"
},
"Hot Food": {
"required": "kitchenDoor",
"optional": "fridge",
"optional": "plateCupboard",
"required": "microwave",
"optional": "cutlery",
"optional": "chair"
}
}}
示例:
如果要匹配的值为chair
,程序将打印出Hot Food
和可选
。
最佳答案
不要使用currentActivity
作为ArrayList
,而是使用HashMap
。因此,将代码的第一行替换如下:
Map<String, String> currentActivity = new HashMap<String, String>();
现在用以下 while 循环替换第三个内部 while 循环(其中匹配 testHarnessSensor
):
while (jsonReader.hasNext()) {
String activityAttribute = jsonReader.nextName();
String n = jsonReader.nextString();
if (testHarnessSensor.equals(n)) {
currentActivity.put(activityName, activityAttribute);
}
}
map currentActivity
将具有预期的结果。要打印每个键值对,请使用以下代码:
for(String key : currentActivity.keySet()){
System.out.println(key + " : " + currentActivity.get(key));
}
关于java - JSON 查找值并返回带有键的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33937456/