我有以下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 -解释

您可以使用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

其他回答

您可以使用DSM流解析库来解析复杂的json和XML文档。DSM只解析一次数据,不会将所有数据加载到内存中。

假设我们有一个Page类来反序列化给定的json数据。

页面类

public class Page {
    private String pageName;
    private String pageImage;
    private List<Sting> postIds;

    // getter/setter

}

创建一个yaml Mapping文件。

result:
  type: object     # result is array
  path: /posts
  fields:
    pageName:
        path: /pageInfo/pageName
    pageImage:
        path: /pageInfo/pagePic
    postIds:
      path: post_id
      type: array

使用DSM提取字段。

DSM dsm=new DSMBuilder(new File("path-to-yaml-config.yaml")).create(Page.class);
Page page= (Page)dsm.toObject(new path-to-json-data.json");

页面变量序列化为json:

{
  "pageName" : "abc",
  "pageImage" : "http://example.com/content.jpg",
  "postIds" : [ "123456789012_123456789012" ]
}

DSM非常适合处理复杂的json和xml。

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

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);

使用minimal-json,它非常快速和容易使用。 你可以从String obj和Stream中解析。

样本数据:

{
  "order": 4711,
  "items": [
    {
      "name": "NE555 Timer IC",
      "cat-id": "645723",
      "quantity": 10,
    },
    {
      "name": "LM358N OpAmp IC",
      "cat-id": "764525",
      "quantity": 2
    }
  ]
}

解析:

JsonObject object = Json.parse(input).asObject();
int orders = object.get("order").asInt();
JsonArray items = object.get("items").asArray();

创建JSON:

JsonObject user = Json.object().add("name", "Sakib").add("age", 23);

Maven:

<dependency>
  <groupId>com.eclipsesource.minimal-json</groupId>
  <artifactId>minimal-json</artifactId>
  <version>0.9.4</version>
</dependency>

你可以使用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