我有以下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"
}
]
}
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();
}
}
}
`
您需要使用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();
}
}
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都是可行的解决方案。