首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Java上解析JSON

如何在Java上解析JSON
EN

Stack Overflow用户
提问于 2017-09-29 04:35:27
回答 3查看 11.9K关注 0票数 -2

我需要解析以下JSON文本来获得"id":176514,

所需的代码是什么?

代码语言:javascript
复制
{
    "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
                }
            }
        ]
    }
}

我试过几次,但是..(我的代码

代码语言:javascript
复制
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:

代码语言:javascript
复制
 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)
EN

回答 3

Stack Overflow用户

发布于 2017-09-29 04:41:14

你需要再深入一层。

代码语言:javascript
复制
JSONObject obj = new JSONObject(str);
JSONObject firstItem = obj.getJSONObject("response").getJSONArray("items").getJSONObject(0);
System.out.println(firstItem.getInt("id"));
票数 3
EN

Stack Overflow用户

发布于 2017-09-29 04:45:35

试试这个:

代码语言:javascript
复制
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");
票数 0
EN

Stack Overflow用户

发布于 2018-08-21 04:18:11

如果您正在解析对象数组

代码语言:javascript
复制
JSONArray jsonArray = new JSONArray(stringToParse);

也不愿照常继续

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46477861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档