JSON使用键查找值和返回对象

时间:2015-11-26 11:26:51

标签: java json gson

我有一个程序搜索JSON对象以匹配值,当它匹配一个值时,我希望它返回对象名称以及与匹配值相关联的键。

这是我目前拥有的代码,它匹配值并根据需要返回对象名称,我需要它返回匹配值的关联键(我使用GSON库)。

testHarnessSensor是要匹配的值,例如chair

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 Foodoptional

1 个答案:

答案 0 :(得分:1)

不要将currentActivity作为ArrayList,而是使用HashMap。因此,请将代码的第一行替换为:

Map<String, String> currentActivity = new HashMap<String, String>();

现在将第3个内部while循环替换为匹配testHarnessSensor,并使用以下while循环:

                while (jsonReader.hasNext()) {                    
                  String activityAttribute = jsonReader.nextName();
                  String n = jsonReader.nextString();                 
                  if (testHarnessSensor.equals(n)) {                 
                    currentActivity.put(activityName, activityAttribute);
                  }
                }

地图currentActivity将具有预期结果。要打印每个键值对,请使用以下代码:

                for(String key : currentActivity.keySet()){
                    System.out.println(key + " : " + currentActivity.get(key));
                }