Java 将 JSON.Simple 与嵌套对象和数组一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24841778/
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-14 15:08:22  来源:igfitidea点击:

Using JSON.Simple with nested objects and arrays

javajson

提问by Novicode

I've decided on using JSON.Simple to parse Java in my application, as apposed to GSON or Hymanson, because both of them seem over complicated for my needs and appeared to need additional class files to work as intended. I have the following JSON:

我决定在我的应用程序中使用 JSON.Simple 来解析 Java,就像 GSON 或 Hymanson 一样,因为它们对于我的需求来说似乎过于复杂,并且似乎需要额外的类文件才能按预期工作。我有以下 JSON:

{
    "request":{
        "act":"rec_load_all",
        "email":"Redacted",
        "tkn":"Redacted",
        "a":"rec_load_all",
        "z":"Redacted"
    },
    "response":{
        "recs":{
            "has_more":false,
            "count":9,
            "objs":[{
                "rec_id":"1385442465",
                "rec_hash":"1825780e334bcd831034bd9ca62",
                "zone_name":"Redacted",
                "name":"Redacted",
                "display_name":"Redacted",
                "type":"A",
                "prio":null,
                "content":"Redacted",
                "display_content":"Redacted",
                "ttl":"1",
                "ttl_ceil":86400,
                "ssl_id":null,
                "ssl_status":null,
                "ssl_expires_on":null,
                "auto_ttl":1,
                "service_mode":"1",
                "props":{
                    "proxiable":1,
                    "cloud_on":1,
                    "cf_open":0,
                    "ssl":0,
                    "expired_ssl":0,
                    "expiring_ssl":0,
                    "pending_ssl":0,
                    "vanity_lock":0
                }
            }]
        }
    },
    "result":"success",
    "msg":null
}

The objsarray lists 9 different items, but I only included one for simplicity. I need to get has_more, count, and the idwithin objs. I've tried:

objs数组列出了 9 个不同的项目,但为了简单起见,我只包含了一个。我需要has_morecount以及idobjs。我试过了:

JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(responseString);
JSONArray objs = (JSONArray) jsonObject.get("objs");
Iterator<JSONObject> iterator = objs.iterator();
while (iterator.hasNext()) {
    JSONObject idObj = (JSONObject) iterator.next();
    String id = (String) idObj.get("rec_id");
    System.out.println(id);
}

But it fires a java.lang.NullPointerExceptionerror, so I'm assuming because it's nested under response -> recs -> objsit isn't getting a value. I'm also following a few year old tutorial, so something could have changed since. If you could explain whats wrong and an example of how to fix it, I would greatly appreciate it, I learn by seeing.

但是它会触发一个java.lang.NullPointerException错误,所以我假设因为它嵌套在response -> recs -> objs它下面没有得到一个值。我也在学习几年前的教程,所以从那以后可能会发生一些变化。如果你能解释什么是错误的以及如何解决它的例子,我将不胜感激,我通过观察学习。

EDIT: Full error

编辑:完全错误

Exception in thread "main" java.lang.NullPointerException
    at ddns.Net.getId(Net.java:46)
    at ddns.DDNS.main(DDNS.java:7)
Java Result: 1

ddns.Net.getId(Net.java:46) | Iterator<JSONObject> iterator = objs.iterator();ddns.DDNS.main(DDNS.java:7) | Just calls the method

ddns.Net.getId(Net.java:46) | Iterator<JSONObject> iterator = objs.iterator();ddns.DDNS.main(DDNS.java:7) |Just calls the method

采纳答案by Carlos Verdes

You have to take any json object from parent and so on, take a look this code (I tried and works):

您必须从父级等获取任何 json 对象,看看这段代码(我尝试过并且有效):

    public static void main(String[] args) throws IOException, ParseException {

    JSONParser jsonParser = new JSONParser();

    InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("json.json");
    InputStreamReader reader = new InputStreamReader(is);
    JSONObject result = (JSONObject) jsonParser.parse(reader);
    JSONObject response = (JSONObject) result.get("response");
    JSONObject recs = (JSONObject) response.get("recs");

    boolean hasMore = (Boolean) recs.get("has_more");
    JSONArray objs = (JSONArray) recs.get("objs");
    System.out.println(recs);
    System.out.println("has more " + hasMore);

    Iterator objIter = objs.iterator();
    int i = 0;
    while (objIter.hasNext()) {
        i++;
        System.out.println(String.format("obj %d: %s", i, objIter.next()));
    }

}

There is another way that for me is easier and is to create a Java Bean with the same structure so... you will parse a hole object, if you are interested on this approach let me know.

还有另一种方法对我来说更容易,它是创建一个具有相同结构的 Java Bean,所以...你将解析一个洞对象,如果你对这种方法感兴趣,请告诉我。

回答by spencemw

@Carlos Verdes pointed me in the right direction.

@Carlos Verdes 为我指明了正确的方向。

From the larger JSON I want put the name of the league, My_League, in a string because its different for each user.

从较大的 JSON 中,我想将联赛的名称My_League, 放在一个字符串中,因为每个用户的名称都不同。

JSON Snippet shortened for brevity:

为简洁起见缩短的 JSON 片段:

{..."name":"Some_Dude", ... ,"expLevel":221,"league":{"id":12345,"name":"My_League","iconUrls":...},...}

Multiple occurrences of the key "name"exist in the JSON and if you look for key "name"again JSON.Simple just retrieves the first occurrence of "name"which would be "Some_Dude"thats right at the beginning.

"name"JSON 中存在多次出现的密钥,如果您"name"再次查找密钥JSON.Simple 只会检索第一次出现的情况,"name""Some_Dude"就是开头。

So to get around that I set that section of the JSON, key "league", into a JSON object and then extracted key "name"from the object to get "My_League"for my string.

因此,为了解决这个问题,我将 JSON 的那部分 key 设置"league"为一个 JSON 对象,然后"name"从该对象中提取密钥以获取"My_League"我的字符串。

JSONObject leagueObj = (JSONObject) each.get("league");
String league = (String)leagueObj.get("name");

The key take away is that when you extract "league":you will get everything after :including all things between {..}up to the next ,that is outside the closing curly }. Which, in my case, is more than you need leaving you to have parse that smaller section, hence the JSON Object.

关键带走的是,当你解压缩"league":后,你会得到一切:,包括之间的所有东西{..}直到下一个,是外面的右大}。在我的情况下,这不仅仅是让您解析那个较小的部分,因此是 JSON 对象。