簡體   English   中英

如何在 Java 上解析 JSON

[英]How to parse JSON on Java

我需要解析以下 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)

你需要再深入一層。

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

嘗試這個:

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");

如果您正在解析對象數組

JSONArray jsonArray = new JSONArray(stringToParse);

比照常繼續

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM