我正在研究一种解析 JSON 文件并收集其内容以供其他地方使用的方法。我目前有一个工作示例如下:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class testJSONParser {
public static void main(String[] args) throws Exception {
List<Map<String, String>> jsonArray = new ArrayList<Map<String, String>>();
BufferedReader br = new BufferedReader(new FileReader("json.txt"));
try {
String line = br.readLine();
while (line != null) {
JSONObject jsonObject = (JSONObject)new JSONParser().parse(line);
Map<String, String> currentLineMap = new HashMap<String, String>();
currentLineMap.put("country", jsonObject.get("country").toString());
currentLineMap.put("size", jsonObject.get("size").toString());
currentLineMap.put("capital", jsonObject.get("capital").toString());
jsonArray.add(currentLineMap);
line = br.readLine();
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
};
}
}
}
我正在使用json 简单库来解析传入的 JSON 字符串。
这是解析文件中的示例字符串。
{"**country**":"Canada","**size**":"9,564,380","**capital**":"Ottawa"}
我的问题是如何获取此代码,并使 put 方法能够动态分配给相应的 Map 。这是我目前拥有的:
for (int i = 0; i < jsonObject.size(); i++) {
currentLineMap.put(jsonObject.???.toString(), jsonObject.get(i).toString());
}
这 ???部分是我难过的地方。获取当前 JSON 行的值很容易。但是如何获取属性值(在 JSON 字符串示例中以粗体突出显示)让我望而却步。有没有一种我可以在我不熟悉的对象上调用的方法?一种不同的更好的方法来遍历这个?还是我从一开始就完全向后做这件事?