返回多个JSON匹配 - Java

时间:2015-11-24 12:51:13

标签: java json gson

我使用GSON搜索JSON文件以匹配值,如果有案例,两个对象中存在一个值,我希望能够返回两个对象,但是那一刻我似乎只能返回找到该值的最后一个对象。

我的JSON文件:

{
  "Activities": {
  "Cold Drink": {
    "optional": "cup",
    "optional": "fridge",
    "required": "juice"
  },
  "Hot Drink": {
    "optional": "cup",
    "optional": "water",
    "optional": "kettle",
    "optional": "sugar",
    "required": "tea/coffee"
  }
}}

我用来匹配值的代码:

public String getCurrentActivity(String testHarnessSensor) {
    LOGGER.log(Level.INFO, "Attempting to get activity.");
    String currentActivity = null;
    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 = activityName;
              }
            }
            jsonReader.endObject();
          }
          jsonReader.endObject();
        }
      }
      jsonReader.endObject();
      jsonReader.close();
    }
    catch (Exception e) {
      System.out.println(e);
    }
    return currentActivity;
  }

1 个答案:

答案 0 :(得分:0)

我写这篇文章时却没有检查它,但这是我评论的精神。

public String[] getCurrentActivity(String testHarnessSensor) {
LOGGER.log(Level.INFO, "Attempting to get activity.");
ArrayList<String> currentActivity = new ArrayList<String>();
try {
  ...
  while (jsonReader.hasNext()) {
    ...                           
      while (jsonReader.hasNext()) {
        ...                        
        while (jsonReader.hasNext()) {                   
          String n = jsonReader.nextName();
          n = jsonReader.nextString();                   
          if (testHarnessSensor.equals(n)) {              
            currentActivity.add(activityName);
          }
        }
        ...
}
catch (Exception e) {
  System.out.println(e);
}
return currentActivity.toArray();

}