从嵌套的 JSON 对象中检索值 [英] Retrieving values from nested JSON Object
问题描述
我有要解析的 JSON 文件.JSON 文件(myfile")的格式如下:
I've got JSON file, which I want to parse. The JSON file ("myfile") has format as follows:
{
"LanguageLevels": {
"1": "Początkujący",
"2": "ŚrednioZaawansowany",
"3": "Zaawansowany",
"4": "Ekspert"
}
}
我想从语言级别检索密钥 2 的值 (ŚrednioZaawansowany).
I want to retrieve value (ŚrednioZaawansowany) of Key 2 from Language Levels.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonSimpleExample {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("myfile");
JSONObject jsonObject = (JSONObject) obj;
JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");
接下来要做什么?我如何迭代它?
What to do next? How I can iterate over it?
推荐答案
也许您没有使用最新版本的 JSON for Java 库.
Maybe you're not using the latest version of a JSON for Java Library.
json-simple
好久没更新了,JSON-Java
2个月前就更新了.
json-simple
has not been updated for a long time, while JSON-Java
was updated 2 month ago.
JSON-Java
可以在 GitHub 上找到,这里是它的 repo 的链接:https://github.com/douglascrockford/JSON-java
JSON-Java
can be found on GitHub, here is the link to its repo: https://github.com/douglascrockford/JSON-java
切换库后,您可以参考我下面的示例代码:
After switching the library, you can refer to my sample code down below:
public static void main(String[] args) {
String JSON = "{"LanguageLevels":{"1":"Pocz\u0105tkuj\u0105cy","2":"\u015arednioZaawansowany","3":"Zaawansowany","4":"Ekspert"}}
";
JSONObject jsonObject = new JSONObject(JSON);
JSONObject getSth = jsonObject.getJSONObject("LanguageLevels");
Object level = getSth.get("2");
System.out.println(level);
}
并且作为 JSON-Java
开源,您可以阅读代码及其文档,他们将指导您完成.
And as JSON-Java
open-sourced, you can read the code and its document, they will guide you through.
希望对您有所帮助.
这篇关于从嵌套的 JSON 对象中检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!