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

当前回答

Java中有许多可用的JSON库。

最臭名昭著的是:Jackson, GSON, Genson, FastJson和org.json。

在选择任何库时,通常应该注意以下三点:

性能 易于使用(代码写起来简单易读)——这与功能有关。 对于移动应用:依赖/jar大小

特别是对于JSON库(以及任何序列化/反序列化库),数据绑定通常也很有趣,因为它消除了编写样板代码来打包/解包数据的需要。

对于1,看到这个基准:https://github.com/fabienrenaud/java-json-benchmark我做了使用JMH比较(杰克逊,gson, genson, fastjson, org。使用stream和databind api实现序列化器和反序列化器的性能。 第二,你可以在网上找到很多例子。上面的基准测试也可以作为例子的来源。

快速总结一下基准:杰克逊的表现比组织好5到6倍。json,比GSON好两倍以上。

对于您的特定示例,下面的代码将使用jackson解码json:

public class MyObj {

    private PageInfo pageInfo;
    private List<Post> posts;

    static final class PageInfo {
        private String pageName;
        private String pagePic;
    }

    static final class Post {
        private String post_id;
        @JsonProperty("actor_id");
        private String actorId;
        @JsonProperty("picOfPersonWhoPosted")
        private String pictureOfPoster;
        @JsonProperty("nameOfPersonWhoPosted")
        private String nameOfPoster;
        private String likesCount;
        private List<String> comments;
        private String timeOfPost;
    }

    private static final ObjectMapper JACKSON = new ObjectMapper();
    public static void main(String[] args) throws IOException {
        MyObj o = JACKSON.readValue(args[0], MyObj.class); // assumes args[0] contains your json payload provided in your question.
    }
}

如果你有任何问题请告诉我。

其他回答

Quick-json解析器非常简单,灵活,快速,可定制。试一试

特点:

Compliant with JSON specification (RFC4627) High-Performance JSON parser Supports Flexible/Configurable parsing approach Configurable validation of key/value pairs of any JSON Hierarchy Easy to use # Very small footprint Raises developer friendly and easy to trace exceptions Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered Validating and Non-Validating parser support Support for two types of configuration (JSON/XML) for using quick-JSON validating parser Requires JDK 1.5 No dependency on external libraries Support for JSON Generation through object serialisation Support for collection type selection during parsing process

它可以这样使用:

JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);

Java中有许多可用的JSON库。

最臭名昭著的是:Jackson, GSON, Genson, FastJson和org.json。

在选择任何库时,通常应该注意以下三点:

性能 易于使用(代码写起来简单易读)——这与功能有关。 对于移动应用:依赖/jar大小

特别是对于JSON库(以及任何序列化/反序列化库),数据绑定通常也很有趣,因为它消除了编写样板代码来打包/解包数据的需要。

对于1,看到这个基准:https://github.com/fabienrenaud/java-json-benchmark我做了使用JMH比较(杰克逊,gson, genson, fastjson, org。使用stream和databind api实现序列化器和反序列化器的性能。 第二,你可以在网上找到很多例子。上面的基准测试也可以作为例子的来源。

快速总结一下基准:杰克逊的表现比组织好5到6倍。json,比GSON好两倍以上。

对于您的特定示例,下面的代码将使用jackson解码json:

public class MyObj {

    private PageInfo pageInfo;
    private List<Post> posts;

    static final class PageInfo {
        private String pageName;
        private String pagePic;
    }

    static final class Post {
        private String post_id;
        @JsonProperty("actor_id");
        private String actorId;
        @JsonProperty("picOfPersonWhoPosted")
        private String pictureOfPoster;
        @JsonProperty("nameOfPersonWhoPosted")
        private String nameOfPoster;
        private String likesCount;
        private List<String> comments;
        private String timeOfPost;
    }

    private static final ObjectMapper JACKSON = new ObjectMapper();
    public static void main(String[] args) throws IOException {
        MyObj o = JACKSON.readValue(args[0], MyObj.class); // assumes args[0] contains your json payload provided in your question.
    }
}

如果你有任何问题请告诉我。

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

主要有两种选择……

Object mapping. When you deserialize JSON data to a number of instances of: 1.1. Some predefined classes, like Maps. In this case, you don't have to design your own POJO classes. Some libraries: org.json.simple https://www.mkyong.com/java/json-simple-example-read-and-write-json/ 1.2. Your own POJO classes. You have to design your own POJO classes to present JSON data, but this may be helpful if you are going to use them into your business logic as well. Some libraries: Gson, Jackson (see http://tutorials.jenkov.com/java-json/index.html)

映射的主要缺点是它会导致大量内存分配(以及GC压力)和CPU占用。

面向流的解析。例如,Gson和Jackson都支持这种轻量级解析。另外,您还可以查看一个自定义的、快速的、无gc的解析器示例https://github.com/anatolygudkov/green-jelly。在需要解析大量数据和对延迟敏感的应用程序中,更倾向于使用这种方式。

我相信最好的做法应该是通过仍在开发中的官方Java JSON API。