如何在 Java 中解析 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2591098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse JSON in Java
提问by Muhammad Maqsoodur Rehman
I have the following JSON text. How can I parse it to get the values of pageName
, pagePic
, post_id
, etc.?
我有以下 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"
}
]
}
回答by rputta
quick-json parseris very straightforward, flexible, very fast and customizable. Try it
quick-json 解析器非常简单、灵活、非常快速和可定制。尝试一下
Features:
特征:
- 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
- 符合 JSON 规范 (RFC4627)
- 高性能 JSON 解析器
- 支持灵活/可配置的解析方法
- 任何 JSON 层次结构的键/值对的可配置验证
- 易于使用 # 占用空间非常小
- 提高开发人员友好且易于跟踪的异常
- 可插入的自定义验证支持 - 键/值可以通过在遇到时配置自定义验证器来验证
- 验证和非验证解析器支持
- 支持两种类型的配置 (JSON/XML) 以使用快速 JSON 验证解析器
- 需要 JDK 1.5
- 不依赖外部库
- 通过对象序列化支持 JSON 生成
- 支持解析过程中的集合类型选择
It can be used like this:
它可以像这样使用:
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
回答by Giovanni Botta
I believe the best practice should be to go through the official Java JSON APIwhich are still work in progress.
我认为最好的做法应该是通过官方的Java JSON API,它仍在进行中。
回答by user1931858
The org.jsonlibrary is easy to use. Example code below:
该org.json库易于使用。示例代码如下:
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");
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......
}
You may find more examples from: Parse JSON in Java
您可以从以下位置找到更多示例:Parse JSON in Java
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
回答by brainmurphy1
This blew my mind with how easy it was. You can just pass a String
holding your JSON to the constructor of a JSONObject in the default org.json package.
这让我大吃一惊,它是多么容易。您可以将String
保存您的 JSON 的对象传递给默认 org.json 包中的 JSONObject 的构造函数。
JSONArray rootOfPage = new JSONArray(JSONString);
Done. Drops microphone.
This works with JSONObjects
as well. After that, you can just look through your hierarchy of Objects
using the get()
methods on your objects.
完毕。滴麦克风。这也适用JSONObjects
。之后,您可以查看在对象上Objects
使用get()
方法的层次结构。
回答by nondescript
If one wants to create Java object from JSON and vice versa, use GSON or HymanSON third party jars etc.
//from object to JSON Gson gson = new Gson(); gson.toJson(yourObject); // from JSON to object yourObject o = gson.fromJson(JSONString,yourObject.class);
But if one just want to parse a JSON string and get some values, (OR create a JSON string from scratch to send over wire) just use JaveEE jar which contains JsonReader, JsonArray, JsonObject etc. You may want to download the implementation of that spec like javax.json. With these two jars I am able to parse the json and use the values.
These APIs actually follow the DOM/SAX parsing model of XML.
Response response = request.get(); // REST call JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class))); JsonArray jsonArray = jsonReader.readArray(); ListIterator l = jsonArray.listIterator(); while ( l.hasNext() ) { JsonObject j = (JsonObject)l.next(); JsonObject ciAttr = j.getJsonObject("ciAttributes");
如果想从 JSON 创建 Java 对象,反之亦然,请使用 GSON 或 HymanSON 第三方 jars 等。
//from object to JSON Gson gson = new Gson(); gson.toJson(yourObject); // from JSON to object yourObject o = gson.fromJson(JSONString,yourObject.class);
但是,如果您只想解析 JSON 字符串并获取一些值,(或从头开始创建 JSON 字符串以通过线路发送)只需使用包含 JsonReader、JsonArray、JsonObject 等的 JaveEE jar。您可能想要下载该实现像 javax.json 这样的规范。有了这两个 jar,我就可以解析 json 并使用这些值。
这些 API 实际上遵循 XML 的 DOM/SAX 解析模型。
Response response = request.get(); // REST call JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class))); JsonArray jsonArray = jsonReader.readArray(); ListIterator l = jsonArray.listIterator(); while ( l.hasNext() ) { JsonObject j = (JsonObject)l.next(); JsonObject ciAttr = j.getJsonObject("ciAttributes");
回答by Sreekanth
Please do something like this:
请做这样的事情:
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(contentString);
String product = (String) jsonObject.get("productId");
回答by LReddy
{
"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 code :
JSONObject obj = new JSONObject(responsejsonobj);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......etc
}
回答by SDekov
For the sake of the example lets assume you have a class Person
with just a name
.
为了这个例子,我们假设你有一个Person
只有name
.
private class Person {
public String name;
public Person(String name) {
this.name = name;
}
}
Google GSON(Maven)
谷歌 GSON( Maven)
My personal favourite as to the great JSON serialisation / de-serialisation of objects.
我个人最喜欢对象的 JSON 序列化/反序列化。
Gson g = new Gson();
Person person = g.fromJson("{\"name\": \"John\"}", Person.class);
System.out.println(person.name); //John
System.out.println(g.toJson(person)); // {"name":"John"}
Update
更新
If you want to get a single attribute out you can do it easily with the Google library as well:
如果您想获取单个属性,也可以使用 Google 库轻松完成:
JsonObject jsonObject = new JsonParser().parse("{\"name\": \"John\"}").getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString()); //John
Org.JSON(Maven)
Org.JSON( Maven)
If you don't need object de-serialisation but to simply get an attribute, you can try org.json (or look GSON example above!)
如果您不需要对象反序列化而只是简单地获取一个属性,您可以尝试 org.json (或查看上面的 GSON 示例!)
JSONObject obj = new JSONObject("{\"name\": \"John\"}");
System.out.println(obj.getString("name")); //John
Hymanson(Maven)
Hyman逊( Maven)
ObjectMapper mapper = new ObjectMapper();
Person user = mapper.readValue("{\"name\": \"John\"}", Person.class);
System.out.println(user.name); //John
回答by Shailendra Singh
If you have some Java class(say Message) representing the JSON string(jsonString), you can use HymansonJSON library with:
如果你有一些 Java 类(比如 Message)表示 JSON 字符串(jsonString),你可以使用HymansonJSON 库:
Message message= new ObjectMapper().readValue(jsonString, Message.class);
and from message object you can fetch any of its attribute.
并且从消息对象中,您可以获取其任何属性。
回答by dade
Almost all the answers given requires a full deserialization of the JSON into a Java object before accessing the value in the property of interest. Another alternative, which does not go this route is to use JsonPATHwhich is like XPath for JSON and allows traversing of JSON objects.
几乎所有给出的答案都需要在访问感兴趣的属性中的值之前将 JSON 完全反序列化为 Java 对象。另一种不走这条路线的替代方法是使用JsonPATH,它类似于 JSON 的 XPath 并允许遍历 JSON 对象。
It is a specification and the good folks at JayWay have created a Java implementation for the specification which you can find here: https://github.com/jayway/JsonPath
这是一个规范,JayWay 的好人已经为该规范创建了一个 Java 实现,您可以在这里找到:https: //github.com/jayway/JsonPath
So basically to use it, add it to your project, eg:
所以基本上要使用它,将它添加到您的项目中,例如:
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>${version}</version>
</dependency>
and to use:
并使用:
String pageName = JsonPath.read(yourJsonString, "$.pageInfo.pageName");
String pagePic = JsonPath.read(yourJsonString, "$.pageInfo.pagePic");
String post_id = JsonPath.read(yourJsonString, "$.pagePosts[0].post_id");
etc...
等等...
Check the JsonPath specification page for more information on the other ways to transverse JSON.
查看 JsonPath 规范页面以获取有关横向 JSON 的其他方法的更多信息。