如何在 Java 中解析 JSON [英] How to parse JSON in Java

查看:26
本文介绍了如何在 Java 中解析 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 JSON 文本.如何解析它以获取 pageNamepagePicpost_id 等的值?

I have the following JSON text. How can I parse it to get the values of pageName, pagePic, post_id, etc.?

    {
       "pageInfo": {
             "pageName": "abc",
             "pagePic": "http://example.com/content.jpg"
        },
        "posts": [
             {
                  "post_id": "123456789012_123456789012",
                  "actor_id": "1234567890",
                  "picOfPersonWhoPosted": "http://example.com/photo.jpg",
                  "nameOfPersonWhoPosted": "Jane Doe",
                  "message": "Sounds cool. Can't wait to see it!",
                  "likesCount": "2",
                  "comments": [],
                  "timeOfPost": "1234567890"
             }
        ]
    }

推荐答案

org.json库易于使用.

请记住(在转换或使用 getJSONObjectgetJSONArray 之类的方法时)以 JSON 表示法

Just remember (while casting or using methods like getJSONObject and getJSONArray) that in JSON notation

  • [ … ] 表示一个数组,因此库会将其解析为 JSONArray
  • { … } 代表一个对象,所以库会将其解析为 JSONObject
  • [ … ] represents an array, so library will parse it to JSONArray
  • { … } represents an object, so library will parse it to JSONObject

示例代码如下:

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
}

您可以从以下位置找到更多示例:在 Java 中解析 JSON

You may find more examples from: Parse JSON in Java

可下载的 jar:http://mvnrepository.com/artifact/org.json/json

这篇关于如何在 Java 中解析 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆