我有以下JSON文本。我如何解析它以获得pageName, pagePic, post_id等的值?

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

当前回答

如果你的数据很简单,你不想要外部依赖,可以使用以下几行代码:

/**
 * A very simple JSON parser for one level, everything quoted.
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, String> simpleParseJson(String json) {
    Map<String, String> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\", "\\").split("\"");
    for (int i = 1; i + 3 < qs.length; i += 4) {
        map.put(qs[i].replace('\u0001', '"'), qs[i + 2].replace('\u0001', '"'));
    }
    return map;
}

这些数据

{"name":"John", "age":"30", "car":"a \"quoted\" back\\slash car"}

生成一个包含

{age=30, car=a "quoted" back\slash car, name=John}

这也可以升级为使用未加引号的值…

/**
 * A very simple JSON parser for one level, names are quoted.
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, String> simpleParseJson(String json) {
    Map<String, String> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\",  "\\").split("\"");
    for (int i = 1; i + 1 < qs.length; i += 4) {
        if (qs[i + 1].trim().length() > 1) {
            String x = qs[i + 1].trim();
            map.put(qs[i].replace('\u0001', '"'), x.substring(1, x.length() - 1).trim().replace('\u0001', '"'));
            i -= 2;
        } else {
            map.put(qs[i].replace('\u0001', '"'), qs[i + 2].replace('\u0001', '"'));
        }
    }
    return map;
}

为了解决复杂的结构,它变得很难看… ... 对不起! !... 但我忍不住把它编码了^^ 这将解析给定的JSON以及更多内容。它产生嵌套的映射和列表。

/**
 * A very simple JSON parser, names are quoted.
 * 
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, Object> simpleParseJson(String json) {
    Map<String, Object> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\", "\\").split("\"");
    int index[] = { 1 };
    recurse(index, map, qs);
    return map;
}

/**
 * Eierlegende Wollmilchsau.
 * 
 * @param index index into array.
 * @param map   the current map to fill.
 * @param qs    the data.
 */
private static void recurse(int[] index, Map<String, Object> map, String[] qs) {
    int i = index[0];
    for (;; i += 4) {
        String end = qs[i - 1].trim(); // check for termination of an object
        if (end.startsWith("}")) {
            qs[i - 1] = end.substring(1).trim();
            i -= 4;
            break;
        }

        String key = qs[i].replace('\u0001', '"');
        String x = qs[i + 1].trim();
        if (x.endsWith("{")) {
            x = x.substring(0, x.length() - 1).trim();
            if (x.endsWith("[")) {
                List<Object> list = new ArrayList<>();
                index[0] = i + 2;
                for (;;) {
                    Map<String, Object> inner = new TreeMap<>();
                    list.add(inner);
                    recurse(index, inner, qs);
                    map.put(key, list);
                    i = index[0];

                    String y = qs[i + 3]; // check for termination of array
                    if (y.startsWith("]")) {
                        qs[i + 3] = y.substring(1).trim();
                        break;
                    }
                }
                continue;
            }

            Map<String, Object> inner = new TreeMap<>();
            index[0] = i + 2;
            recurse(index, inner, qs);
            map.put(key, inner);
            i = index[0];
            continue;
        }
        if (x.length() > 1) { // unquoted
            String value = x.substring(1, x.length() - 1).trim().replace('\u0001', '"');
            if ("[]".equals(value)) // handle empty array
                map.put(key, new ArrayList<>());
            else
                map.put(key, value);
            i -= 2;
        } else {
            map.put(key, qs[i + 2].replace('\u0001', '"'));
        }
    }
    index[0] = i;
}

yield -如果你打印地图:

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

其他回答

为了便于示例,让我们假设您有一个只有名称的Person类。

private class Person {
    public String name;

    public Person(String name) {
        this.name = name;
    }
}

谷歌GSON (Maven)

我个人最喜欢的JSON对象序列化/反序列化。

Gson g = new Gson();

Person person = g.fromJson("{\"name\": \"John\"}", Person.class);
System.out.println(person.name); //John

System.out.println(g.toJson(person)); // {"name":"John"}

更新

如果你想获取单个属性,你可以很容易地使用谷歌库:

JsonObject jsonObject = new JsonParser().parse("{\"name\": \"John\"}").getAsJsonObject();

System.out.println(jsonObject.get("name").getAsString()); //John

Org。JSON (Maven)

如果您不需要对象反序列化,而只是获得一个属性,您可以尝试org。json(或查看上面的GSON示例!)

JSONObject obj = new JSONObject("{\"name\": \"John\"}");

System.out.println(obj.getString("name")); //John

杰克逊(Maven)

ObjectMapper mapper = new ObjectMapper();
Person user = mapper.readValue("{\"name\": \"John\"}", Person.class);

System.out.println(user.name); //John

org。Json库易于使用。

只要记住(在强制转换或使用getJSONObject和getJSONArray等方法时)JSON表示法

[…]表示一个数组,因此库将把它解析为JSONArray {…}表示一个对象,因此库将把它解析为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");
    ......
}

你可以从以下几个方面找到更多的例子

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

你可以使用Jayway JsonPath。下面是一个GitHub链接,包括源代码、pom细节和良好的文档。

https://github.com/jayway/JsonPath

请按照以下步骤操作。

步骤1:使用Maven在类路径中添加jayway JSON路径依赖项,或者下载JAR文件并手动添加它。

<dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>2.2.0</version>
</dependency>

步骤2:请将输入的JSON保存为本示例的文件。在我的情况下,我将JSON保存为sampleJson.txt。注意,pageInfo和posts之间没有逗号。

步骤3:使用bufferedReader从上面的文件中读取JSON内容,并将其保存为String。

BufferedReader br = new BufferedReader(new FileReader("D:\\sampleJson.txt"));

StringBuilder sb = new StringBuilder();
String line = br.readLine();

while (line != null) {
    sb.append(line);
    sb.append(System.lineSeparator());
    line = br.readLine();
}
br.close();
String jsonInput = sb.toString();

步骤4:使用jayway JSON解析器解析JSON字符串。

Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonInput);

第五步:像下面这样阅读细节。

String pageName = JsonPath.read(document, "$.pageInfo.pageName");
String pagePic = JsonPath.read(document, "$.pageInfo.pagePic");
String post_id = JsonPath.read(document, "$.posts[0].post_id");

System.out.println("$.pageInfo.pageName " + pageName);
System.out.println("$.pageInfo.pagePic " + pagePic);
System.out.println("$.posts[0].post_id " + post_id);

输出将是:

$.pageInfo.pageName = abc
$.pageInfo.pagePic = http://example.com/content.jpg
$.posts[0].post_id  = 123456789012_123456789012

The below example shows how to read the text in the question, represented as the "jsonText" variable. This solution uses the Java EE7 javax.json API (which is mentioned in some of the other answers). The reason I've added it as a separate answer is that the following code shows how to actually access some of the values shown in the question. An implementation of the javax.json API would be required to make this code run. The full package for each of the classes required was included as I didn't want to declare "import" statements.

javax.json.JsonReader jr = 
    javax.json.Json.createReader(new StringReader(jsonText));
javax.json.JsonObject jo = jr.readObject();

//Read the page info.
javax.json.JsonObject pageInfo = jo.getJsonObject("pageInfo");
System.out.println(pageInfo.getString("pageName"));

//Read the posts.
javax.json.JsonArray posts = jo.getJsonArray("posts");
//Read the first post.
javax.json.JsonObject post = posts.getJsonObject(0);
//Read the post_id field.
String postId = post.getString("post_id");

现在,在大家对这个答案投反对票之前因为它没有使用GSON, org。json, Jackson或任何其他可用的第三方框架,它是每个问题解析所提供文本的“所需代码”的示例。我很清楚JDK 9没有考虑遵守当前标准JSR 353,因此JSR 353规范应该与任何其他第三方JSON处理实现一样对待。

如果你的数据很简单,你不想要外部依赖,可以使用以下几行代码:

/**
 * A very simple JSON parser for one level, everything quoted.
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, String> simpleParseJson(String json) {
    Map<String, String> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\", "\\").split("\"");
    for (int i = 1; i + 3 < qs.length; i += 4) {
        map.put(qs[i].replace('\u0001', '"'), qs[i + 2].replace('\u0001', '"'));
    }
    return map;
}

这些数据

{"name":"John", "age":"30", "car":"a \"quoted\" back\\slash car"}

生成一个包含

{age=30, car=a "quoted" back\slash car, name=John}

这也可以升级为使用未加引号的值…

/**
 * A very simple JSON parser for one level, names are quoted.
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, String> simpleParseJson(String json) {
    Map<String, String> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\",  "\\").split("\"");
    for (int i = 1; i + 1 < qs.length; i += 4) {
        if (qs[i + 1].trim().length() > 1) {
            String x = qs[i + 1].trim();
            map.put(qs[i].replace('\u0001', '"'), x.substring(1, x.length() - 1).trim().replace('\u0001', '"'));
            i -= 2;
        } else {
            map.put(qs[i].replace('\u0001', '"'), qs[i + 2].replace('\u0001', '"'));
        }
    }
    return map;
}

为了解决复杂的结构,它变得很难看… ... 对不起! !... 但我忍不住把它编码了^^ 这将解析给定的JSON以及更多内容。它产生嵌套的映射和列表。

/**
 * A very simple JSON parser, names are quoted.
 * 
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, Object> simpleParseJson(String json) {
    Map<String, Object> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\", "\\").split("\"");
    int index[] = { 1 };
    recurse(index, map, qs);
    return map;
}

/**
 * Eierlegende Wollmilchsau.
 * 
 * @param index index into array.
 * @param map   the current map to fill.
 * @param qs    the data.
 */
private static void recurse(int[] index, Map<String, Object> map, String[] qs) {
    int i = index[0];
    for (;; i += 4) {
        String end = qs[i - 1].trim(); // check for termination of an object
        if (end.startsWith("}")) {
            qs[i - 1] = end.substring(1).trim();
            i -= 4;
            break;
        }

        String key = qs[i].replace('\u0001', '"');
        String x = qs[i + 1].trim();
        if (x.endsWith("{")) {
            x = x.substring(0, x.length() - 1).trim();
            if (x.endsWith("[")) {
                List<Object> list = new ArrayList<>();
                index[0] = i + 2;
                for (;;) {
                    Map<String, Object> inner = new TreeMap<>();
                    list.add(inner);
                    recurse(index, inner, qs);
                    map.put(key, list);
                    i = index[0];

                    String y = qs[i + 3]; // check for termination of array
                    if (y.startsWith("]")) {
                        qs[i + 3] = y.substring(1).trim();
                        break;
                    }
                }
                continue;
            }

            Map<String, Object> inner = new TreeMap<>();
            index[0] = i + 2;
            recurse(index, inner, qs);
            map.put(key, inner);
            i = index[0];
            continue;
        }
        if (x.length() > 1) { // unquoted
            String value = x.substring(1, x.length() - 1).trim().replace('\u0001', '"');
            if ("[]".equals(value)) // handle empty array
                map.put(key, new ArrayList<>());
            else
                map.put(key, value);
            i -= 2;
        } else {
            map.put(key, qs[i + 2].replace('\u0001', '"'));
        }
    }
    index[0] = i;
}

yield -如果你打印地图:

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