【发布时间】:2015-08-19 11:08:01
【问题描述】:
我有一段代码正在搜索 JSON 文件以查找匹配项,一旦找到匹配项,它会将 JSON 文件中的关联值分配给变量 currentLocation。我要问的问题是如何将此值分配给currentLocation 并在while 循环之外访问它?
代码块:
String currentLocation = null;
try {
JsonReader jsonReader = new JsonReader(new FileReader("src/resources/objectLocation.json"));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String nameRoot = jsonReader.nextName();
if (nameRoot.equals("locations")) {
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String n = jsonReader.nextName();
n = jsonReader.nextString();
if (n.equals(currentObject)) {
currentLocation = name;
}
}
jsonReader.endObject();
}
jsonReader.endObject();
}
}
jsonReader.endObject();
jsonReader.close();
}
catch (Exception e) {
}
return currentLocation + " " + currentObject;
据我了解,正在发生的事情是我正在寻找的值被分配给currentLocation OK,但随后它超出了我试图访问它的范围,因此返回 null。
我尝试将其声明为:
final String currentLocation;
然后给我错误variable currentLocation might be assigned in a loop,当然是。
我如何在我的 return 语句的 while 循环中访问 currentLocation 的值?
【问题讨论】:
-
为什么不将
currentLocation = name替换为return name+" "+currentObject(将jsonReader.close()移至finally块)? -
您是否考虑过您的代码可能引发异常的可能性?因此,您将 currentLocation 设为 null?
-
我给
currentLocation分配了一个假值,并成功返回。 -
@TagirValeev 如果我这样做,我的代码会在
catch块之后抱怨缺少return。有没有办法解决这个问题? -
@Colin747,当您的解析失败或没有找到(可能为空?)时,只需返回适当的内容。如果您认为这种情况永远不会发生,只需将
throw new InternalError();放在最后一行即可。
标签: java json variables while-loop scope