我有以下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();
}
}