我有以下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"
    }
  ]
}

当前回答

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

其他回答

由于还没有人提到它,这里是一个使用Nashorn (Java 8的JavaScript运行时部分,但在Java 11中已弃用)的解决方案的开始。

解决方案

private static final String EXTRACTOR_SCRIPT =
    "var fun = function(raw) { " +
    "var json = JSON.parse(raw); " +
    "return [json.pageInfo.pageName, json.pageInfo.pagePic, json.posts[0].post_id];};";

public void run() throws ScriptException, NoSuchMethodException {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    engine.eval(EXTRACTOR_SCRIPT);
    Invocable invocable = (Invocable) engine;
    JSObject result = (JSObject) invocable.invokeFunction("fun", JSON);
    result.values().forEach(e -> System.out.println(e));
}

性能比较

我编写的JSON内容包含三个数组,分别为20、20和100个元素。我只想从第三个数组中获取100个元素。我使用下面的JavaScript函数来解析和获取我的条目。

var fun = function(raw) {JSON.parse(raw).entries};

使用Nashorn运行一百万次调用需要7.5~7.8秒

(JSObject) invocable.invokeFunction("fun", json);

org。Json需要20~21秒

new JSONObject(JSON).getJSONArray("entries");

杰克逊用时6.5~7秒

mapper.readValue(JSON, Entries.class).getEntries();

在这种情况下,Jackson的性能比Nashorn好,后者的性能比org.json好得多。 Nashorn API比org更难使用。json或Jackson的。根据您的需求,Jackson和Nashorn都是可行的解决方案。

您可以使用Gson库来解析JSON字符串。

Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonAsString, JsonObject.class);

String pageName = jsonObject.getAsJsonObject("pageInfo").get("pageName").getAsString();
String pagePic = jsonObject.getAsJsonObject("pageInfo").get("pagePic").getAsString();
String postId = jsonObject.getAsJsonArray("posts").get(0).getAsJsonObject().get("post_id").getAsString();

你也可以循环"posts"数组,如下所示:

JsonArray posts = jsonObject.getAsJsonArray("posts");
for (JsonElement post : posts) {
  String postId = post.getAsJsonObject().get("post_id").getAsString();
  //do something
}

Gson很容易学习和实现,我们需要知道的是以下两种方法

toJson() -将Java对象转换为JSON格式 fromJson() -将JSON转换为Java对象

`

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;

public class GsonExample {
    public static void main(String[] args) {

    Gson gson = new Gson();

    try {

        BufferedReader br = new BufferedReader(
            new FileReader("c:\\file.json"));

        //convert the json string back to object
        DataObject obj = gson.fromJson(br, DataObject.class);

        System.out.println(obj);

    } catch (IOException e) {
        e.printStackTrace();
    }

    }
}

`

A -解释

您可以使用Jackson库,将JSON字符串绑定到POJO(普通旧Java对象)实例中。POJO只是一个只有私有字段和公共getter/setter方法的类。Jackson将遍历这些方法(使用反射),并将JSON对象映射到POJO实例,因为类的字段名与JSON对象的字段名相匹配。

在JSON对象中,它实际上是一个复合对象,主对象由两个子对象组成。因此,我们的POJO类应该具有相同的层次结构。我将把整个JSON对象称为Page对象。Page对象由PageInfo对象和Post对象数组组成。

所以我们必须创建三个不同的POJO类;

页面类,PageInfo类和Post实例数组的组合 PageInfo类 文章类

我唯一用过的包是Jackson ObjectMapper,我们做的是绑定数据;

com.fasterxml.jackson.databind.ObjectMapper

所需的依赖项,jar文件如下所示;

jackson-core-2.5.1.jar jackson-databind-2.5.1.jar jackson-annotations-2.5.0.jar

这里是所需的代码;

主POJO类:页

package com.levo.jsonex.model;

public class Page {
    
    private PageInfo pageInfo;
    private Post[] posts;

    public PageInfo getPageInfo() {
        return pageInfo;
    }

    public void setPageInfo(PageInfo pageInfo) {
        this.pageInfo = pageInfo;
    }

    public Post[] getPosts() {
        return posts;
    }

    public void setPosts(Post[] posts) {
        this.posts = posts;
    }
    
}

C -儿童POJO类:PageInfo

package com.levo.jsonex.model;

public class PageInfo {
    
    private String pageName;
    private String pagePic;
    
    public String getPageName() {
        return pageName;
    }
    
    public void setPageName(String pageName) {
        this.pageName = pageName;
    }
    
    public String getPagePic() {
        return pagePic;
    }
    
    public void setPagePic(String pagePic) {
        this.pagePic = pagePic;
    }
    
}

D -儿童POJO类:Post

package com.levo.jsonex.model;

public class Post {
    
    private String post_id;
    private String actor_id;
    private String picOfPersonWhoPosted;
    private String nameOfPersonWhoPosted;
    private String message;
    private int likesCount;
    private String[] comments;
    private int timeOfPost;

    public String getPost_id() {
        return post_id;
    }

    public void setPost_id(String post_id) {
        this.post_id = post_id;
    }

    public String getActor_id() {
        return actor_id;
    }

    public void setActor_id(String actor_id) {
        this.actor_id = actor_id;
    }

    public String getPicOfPersonWhoPosted() {
        return picOfPersonWhoPosted;
    }
    
    public void setPicOfPersonWhoPosted(String picOfPersonWhoPosted) {
        this.picOfPersonWhoPosted = picOfPersonWhoPosted;
    }

    public String getNameOfPersonWhoPosted() {
        return nameOfPersonWhoPosted;
    }

    public void setNameOfPersonWhoPosted(String nameOfPersonWhoPosted) {
        this.nameOfPersonWhoPosted = nameOfPersonWhoPosted;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getLikesCount() {
        return likesCount;
    }

    public void setLikesCount(int likesCount) {
        this.likesCount = likesCount;
    }

    public String[] getComments() {
        return comments;
    }

    public void setComments(String[] comments) {
        this.comments = comments;
    }

    public int getTimeOfPost() {
        return timeOfPost;
    }

    public void setTimeOfPost(int timeOfPost) {
        this.timeOfPost = timeOfPost;
    }
    
}

E -样本JSON文件:sampleJSONFile.json

我刚刚将JSON示例复制到这个文件中,并将其放在项目文件夹下。

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

F -演示代码

package com.levo.jsonex;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.levo.jsonex.model.Page;
import com.levo.jsonex.model.PageInfo;
import com.levo.jsonex.model.Post;

public class JSONDemo {
    
    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();
        
        try {
            Page page = objectMapper.readValue(new File("sampleJSONFile.json"), Page.class);
            
            printParsedObject(page);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    
    private static void printParsedObject(Page page) {
        printPageInfo(page.getPageInfo());
        System.out.println();
        printPosts(page.getPosts());
    }

    private static void printPageInfo(PageInfo pageInfo) {
        System.out.println("Page Info;");
        System.out.println("**********");
        System.out.println("\tPage Name : " + pageInfo.getPageName());
        System.out.println("\tPage Pic  : " + pageInfo.getPagePic());
    }
    
    private static void printPosts(Post[] posts) {
        System.out.println("Page Posts;");
        System.out.println("**********");
        for(Post post : posts) {
            printPost(post);
        }
    }
    
    private static void printPost(Post post) {
        System.out.println("\tPost Id                   : " + post.getPost_id());
        System.out.println("\tActor Id                  : " + post.getActor_id());
        System.out.println("\tPic Of Person Who Posted  : " + post.getPicOfPersonWhoPosted());
        System.out.println("\tName Of Person Who Posted : " + post.getNameOfPersonWhoPosted());
        System.out.println("\tMessage                   : " + post.getMessage());
        System.out.println("\tLikes Count               : " + post.getLikesCount());
        System.out.println("\tComments                  : " + Arrays.toString(post.getComments()));
        System.out.println("\tTime Of Post              : " + post.getTimeOfPost());
    }
    
}

G -演示输出

Page Info;
****(*****
    Page Name : abc
    Page Pic  : http://example.com/content.jpg
Page Posts;
**********
    Post Id                   : 123456789012_123456789012
    Actor Id                  : 1234567890
    Pic Of Person Who Posted  : http://example.com/photo.jpg
    Name Of Person Who Posted : Jane Doe
    Message                   : Sounds cool. Can't wait to see it!
    Likes Count               : 2
    Comments                  : []
    Time Of Post              : 1234567890

本页的热门答案使用了太简单的例子,比如只有一个属性的对象(例如{name: value})。我认为这个简单但真实的例子可以帮助到一些人。

这是谷歌Translate API返回的JSON:

{
  "data": 
     {
        "translations": 
          [
            {
              "translatedText": "Arbeit"
             }
          ]
     }
}

我想检索“translatedText”属性的值。“Arbeit”使用谷歌的Gson。

两种可能的方法:

Retrieve just one needed attribute String json = callToTranslateApi("work", "de"); JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject(); return jsonObject.get("data").getAsJsonObject() .get("translations").getAsJsonArray() .get(0).getAsJsonObject() .get("translatedText").getAsString(); Create Java object from JSON class ApiResponse { Data data; class Data { Translation[] translations; class Translation { String translatedText; } } } ... Gson g = new Gson(); String json =callToTranslateApi("work", "de"); ApiResponse response = g.fromJson(json, ApiResponse.class); return response.data.translations[0].translatedText;