Java 从嵌套的 JSON 对象中检索值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20899839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:07:32  来源:igfitidea点击:

Retrieving values from nested JSON Object

javajsonparsingnested

提问by m.aibin

I've got JSON file, which I want to parse. The JSON file ("myfile") has format as follows:

我有要解析的 JSON 文件。JSON 文件(“myfile”)的格式如下:

{
    "LanguageLevels": {
        "1": "Pocz?tkuj?cy",
        "2": "?rednioZaawansowany",
        "3": "Zaawansowany",
        "4": "Ekspert"
    }
}

I want to retrieve value (?rednioZaawansowany) of Key 2 from Language Levels.

我想从语言级别检索密钥 2 的值 (?rednioZaawansowany)。

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?

接下来做什么?我如何迭代它?

采纳答案by Xiao Liang

Maybe you're not using the latest version of a JSON for Java Library.

也许您没有使用最新版本的 JSON for Java 库。

json-simplehas not been updated for a long time, while JSON-Javawas updated 2 month ago.

json-simple好久没更新了,JSON-Java2个月前就更新了。

JSON-Javacan be found on GitHub, here is the link to its repo: https://github.com/douglascrockford/JSON-java

JSON-Java可以在 GitHub 上找到,这里是它的 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\"}}\n";

    JSONObject jsonObject = new JSONObject(JSON);
    JSONObject getSth = jsonObject.getJSONObject("LanguageLevels");
    Object level = getSth.get("2");

    System.out.println(level);
}

And as JSON-Javaopen-sourced, you can read the code and its document, they will guide you through.

作为JSON-Java开源,您可以阅读代码及其文档,他们将指导您完成。

Hope that it helps.

希望它有帮助。

回答by dehlen

JSONArray jsonChildArray = (JSONArray) jsonChildArray.get("LanguageLevels");
    JSONObject secObject = (JSONObject) jsonChildArray.get(1);

I think this should work, but i do not have the possibility to test it at the moment..

我认为这应该有效,但我目前无法对其进行测试..

回答by Jakub Kotowski

You can see that JSONObjectextends a HashMap, so you can simply use it as a HashMap:

您可以看到JSONObject扩展了 a HashMap,因此您可以简单地将其用作 HashMap:

JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");
for (Map.Entry in jsonChildOBject.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

回答by eabyshev

To see all keys of Jsonobject use this

要查看 Jsonobject 的所有键,请使用它

    String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\u0105tkuj\u0105cy\",\"2\":\"\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
    JSONObject obj = new JSONObject(JSON);
    Iterator iterator = obj.keys();
    String key = null;
    while (iterator.hasNext()) {
        key = (String) iterator.next();
        System.out.pritnln(key);
    } 

回答by preetesh gurjar

You will have to iterate step by step into nested JSON.

您必须逐步迭代到嵌套的 JSON 中。

for e.g a JSON received from Google geocoding api

例如从 Google 地理编码 api 收到的 JSON

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Bhopal",
               "short_name" : "Bhopal",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Bhopal",
               "short_name" : "Bhopal",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Madhya Pradesh",
               "short_name" : "MP",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Bhopal, Madhya Pradesh, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 23.3326697,
                  "lng" : 77.5748062
               },
               "southwest" : {
                  "lat" : 23.0661497,
                  "lng" : 77.2369767
               }
            },
            "location" : {
               "lat" : 23.2599333,
               "lng" : 77.412615
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 23.3326697,
                  "lng" : 77.5748062
               },
               "southwest" : {
                  "lat" : 23.0661497,
                  "lng" : 77.2369767
               }
            }
         },
         "place_id" : "ChIJvY_Wj49CfDkR-NRy1RZXFQI",
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

I shall iterate in below given fashionto "location" : { "lat" : 23.2599333, "lng" : 77.412615

我将以下面给定的方式迭代到 "location" : { "lat" : 23.2599333, "lng" : 77.412615

//recieve JSON in json object

//在json对象中接收JSON

        JSONObject json = new JSONObject(output.toString());
        JSONArray result = json.getJSONArray("results");
        JSONObject result1 = result.getJSONObject(0);
        JSONObject geometry = result1.getJSONObject("geometry");
        JSONObject locat = geometry.getJSONObject("location");

        //"iterate onto level of location";

        double lat = locat.getDouble("lat");
        double lng = locat.getDouble("lng");