简体   繁体   English

对嵌套对象和数组使用JSON.Simple

[英]Using JSON.Simple with nested objects and arrays

I've decided on using JSON.Simple to parse Java in my application, as apposed to GSON or Jackson, because both of them seem over complicated for my needs and appeared to need additional class files to work as intended. 我已经决定使用JSON.Simple来解析应用程序中的Java(与GSON或Jackson一样),因为对于我来说,它们看起来都过于复杂,并且似乎需要按预期工作的其他类文件。 I have the following JSON: 我有以下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 objs array lists 9 different items, but I only included one for simplicity. objs数组列出了9个不同的项目,但为简单起见,我仅包括了一个项目。 I need to get has_more , count , and the id within objs . 我需要得到has_morecountidobjs I've tried: 我试过了:

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.NullPointerException error, so I'm assuming because it's nested under response -> recs -> objs it isn't getting a value. 但是它会引发java.lang.NullPointerException错误,所以我假设是因为它嵌套在response -> recs -> objs ,因此没有值。 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. 如果您能解释什么是错误的以及如何解决该错误的示例,那么我将不胜感激。

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

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,因此...如果您对此方法感兴趣,可以解析一个Hole对象,请告诉我。

@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. JSON中多次出现键"name" ,如果再次查找键"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的该部分(键"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 } . 关键带走的是,当你提取"league":你会得到一切后:包括它们之间的所有的东西{..}到下一个,那就是外面的右花} Which, in my case, is more than you need leaving you to have parse that smaller section, hence the JSON Object. 就我而言,这远远超出了您只需要解析该较小部分(即JSON对象)的余地。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM