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

当前回答

您需要使用JsonNode和来自jackson库的ObjectMapper类来获取Json树的节点。在pom.xml中添加以下依赖项以获得对Jackson类的访问权。

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.5</version>
</dependency>

你应该尝试下面的代码,这将工作:

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

class JsonNodeExtractor{

    public void convertToJson(){

        String filepath = "c:\\data.json";
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node =  mapper.readTree(filepath);

        // create a JsonNode for every root or subroot element in the Json String
        JsonNode pageInfoRoot = node.path("pageInfo");

        // Fetching elements under 'pageInfo'
        String pageName =  pageInfoRoot.path("pageName").asText();
        String pagePic = pageInfoRoot.path("pagePic").asText();

        // Now fetching elements under posts
        JsonNode  postsNode = node.path("posts");
        String post_id = postsNode .path("post_id").asText();
        String nameOfPersonWhoPosted = postsNode 
        .path("nameOfPersonWhoPosted").asText();
    }
}

其他回答

这让我惊讶于它是多么简单。你可以在默认的组织中传递一个包含JSON的String给JSONObject的构造函数。json包。

JSONArray rootOfPage =  new JSONArray(JSONString);

完成了。滴麦克风。 这也适用于JSONObjects。在此之后,您可以使用对象上的get()方法查看对象的层次结构。

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

Jsoniter (jsoniterator)是一个相对较新的和简单的json库,旨在简单和快速。反序列化json数据所需要做的就是

JsonIterator.deserialize(jsonData, int[].class);

其中jsonData是json数据的字符串。

去官方网站看看吧 获取更多信息。

您可以使用JsonNode来表示JSON字符串的结构化树。它是无处不在的杰克逊图书馆的一部分。

ObjectMapper mapper = new ObjectMapper();
JsonNode yourObj = mapper.readTree("{\"k\":\"v\"}");

首先,您需要选择一个实现库来执行此操作。

用于JSON处理的Java API (JSR 353)提供了使用对象模型和流API来解析、生成、转换和查询JSON的可移植API。

参考实现在这里:https://jsonp.java.net/

下面是JSR 353的实现列表:

哪些API实现了JSR-353 (JSON)

为了帮助你决定…我也找到了这篇文章:

http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/

如果您选择Jackson,这里有一篇关于使用Jackson在JSON和Java之间转换的好文章:https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

希望能有所帮助!