返回多个JSON匹配-Java



我使用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;
  }

我写这篇文章时无法检查,但这就是我评论的精神。

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();

}

最新更新