如何在Java上解析JSON

时间:2017-09-28 20:35:27

标签: java json

我有以下JSON文本需要解析才能获得“id”:176514,

所需代码是什么?

{
    "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
                }
            }
        ]
    }
}

我尝试了一些但是......( 我的代码

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 我的错误:

 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)

3 个答案:

答案 0 :(得分:1)

你需要更深层次。

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

答案 1 :(得分:0)

试试这个:

listItems

答案 2 :(得分:0)

如果要解析对象数组

JSONArray jsonArray = new JSONArray(stringToParse);

比平时继续