简体   繁体   中英

How to parse JSON on Java

I have the following JSON text that I need to parse to get "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:

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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