简体   繁体   English

如何在 Java 上解析 JSON

[英]How to parse JSON on Java

I have the following JSON text that I need to parse to get "id": 176514,我需要解析以下 JSON 文本以获取“id”:176514,

What is the required code?所需的代码是什么?

{
    "response": {
        "count": 10307,
        "items": [
            {
                "id": 176514,
                "from_id": -114200945,
                "owner_id": -114200945,
                "date": 1506629224,
                "marked_as_ads": 0,
                "post_type": "post",
                "text": "-я с разбитым сердцем сука,но я всё равно влюблённый.",
                "post_source": {
                    "type": "api"
                },
                "comments": {
                    "count": 1,
                    "groups_can_post": true,
                    "can_post": 1
                },
                "likes": {
                    "count": 103,
                    "user_likes": 0,
                    "can_like": 1,
                    "can_publish": 1
                },
                "reposts": {
                    "count": 3,
                    "user_reposted": 0
                },
                "views": {
                    "count": 1022
                }
            }
        ]
    }
}

I try some times but.. ( my code我尝试了几次但是..(我的代码

import java.io.IOException;
import java.net.URL;
import java.util.Scanner;

import org.json.JSONArray;
import org.json.JSONObject;


class VK{



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

     URL url = new URL("my url which return JSON structure");
    Scanner scan = new Scanner(url.openStream());
    String str = new String();

    while (scan.hasNext())
        str += scan.nextLine();
    scan.close();
    JSONObject obj = new JSONObject(str);


    JSONObject res = obj.getJSONArray("items").getJSONObject(0);
    System.out.println(res.getInt("id"));           
}
}

Eclipse my errors: Eclipse 我的错误:

 Exception in thread "main" org.json.JSONException: JSONObject["items"] not found.
        at org.json.JSONObject.get(JSONObject.java:472)
        at org.json.JSONObject.getJSONArray(JSONObject.java:619)
        at VK.main(VK.java:26)

You need to go one more level deep.你需要再深入一层。

JSONObject obj = new JSONObject(str);
JSONObject firstItem = obj.getJSONObject("response").getJSONArray("items").getJSONObject(0);
System.out.println(firstItem.getInt("id"));

try this:尝试这个:

JSONObject obj = new JSONObject(str);//assuming that obj is the same object as in the example

//to get the id
int id = obj.getJSONObject("response").getJSONArray("items").getJSONObject(0).getInt("id");

In case that you are parsing Array of objects如果您正在解析对象数组

JSONArray jsonArray = new JSONArray(stringToParse);

than continue as usual比照常继续

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

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