Muh*_*man 971 java parsing json
我有以下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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
小智 715
该org.json库易于使用.示例代码如下:
import org.json.*;
JSONObject obj = new JSONObject(" .... ");
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");
......
}
Run Code Online (Sandbox Code Playgroud)
您可以从以下位置找到更多示例:使用Java解析JSON
可下载的jar:http: //mvnrepository.com/artifact/org.json/json
SDe*_*kov 513
为了这个例子,我们假设你有一个Person只有一个类的类name.
private class Person {
public String name;
public Person(String name) {
this.name = name;
}
}
Run Code Online (Sandbox Code Playgroud)
我个人最喜欢的是对象的优秀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"}
Run Code Online (Sandbox Code Playgroud)
更新
如果您想要获得单个属性,您也可以使用Google库轻松完成:
JsonObject jsonObject = new JsonParser().parse("{\"name\": \"John\"}").getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString()); //John
Run Code Online (Sandbox Code Playgroud)
如果您不需要对象反序列化但只需获取属性,您可以尝试org.json(或者查看上面的GSON示例!)
JSONObject obj = new JSONObject("{\"name\": \"John\"}");
System.out.println(obj.getString("name")); //John
Run Code Online (Sandbox Code Playgroud)
ObjectMapper mapper = new ObjectMapper();
Person user = mapper.readValue("{\"name\": \"John\"}", Person.class);
System.out.println(user.name); //John
Run Code Online (Sandbox Code Playgroud)
non*_*ipt 100
如果想要从JSON创建Java对象,反之亦然,请使用GSON或JACKSON第三方罐等.
//from object to JSON
Gson gson = new Gson();
gson.toJson(yourObject);
// from JSON to object
yourObject o = gson.fromJson(JSONString,yourObject.class);
Run Code Online (Sandbox Code Playgroud)但是,如果只想解析一个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");
Run Code Online (Sandbox Code Playgroud)小智 71
quick-json解析器非常简单,灵活,非常快速且可定制.试试吧
特征:
它可以像这样使用:
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
Run Code Online (Sandbox Code Playgroud)
Lev*_*glu 37
您可以使用Jackson库将JSON String绑定到POJO(Plain Old Java Object)实例.POJO只是一个只有私有字段和公共getter/setter方法的类.Jackson将遍历方法(使用反射),并将JSON对象映射到POJO实例,因为类的字段名称适合JSON对象的字段名称.
在您的JSON对象(实际上是一个复合对象)中,主对象包含两个子对象.因此,我们的POJO类应该具有相同的层次结构.我将整个JSON对象称为Page对象.页面对象由PageInfo对象和Post对象数组组成.
所以我们必须创建三个不同的POJO类;
我使用的唯一包是Jackson ObjectMapper,我们所做的是绑定数据;
com.fasterxml.jackson.databind.ObjectMapper
Run Code Online (Sandbox Code Playgroud)
所需的依赖项,jar文件如下所示;
这是必需的代码;
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我刚刚将您的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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
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());
}
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
dad*_*ade 34
几乎所有给出的答案都需要在访问感兴趣的属性中的值之前将JSON完全反序列化为Java对象.另一种不采用这种方法的方法是使用JsonPATH,它类似于XPath for JSON,并允许遍历JSON对象.
这是一个规范,JayWay的优秀人员为规范创建了一个Java实现,您可以在这里找到:https://github.com/jayway/JsonPath
所以基本上使用它,将它添加到您的项目中,例如:
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>${version}</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
并使用:
String pageName = JsonPath.read(yourJsonString, "$.pageInfo.pageName");
String pagePic = JsonPath.read(yourJsonString, "$.pageInfo.pagePic");
String post_id = JsonPath.read(yourJsonString, "$.pagePosts[0].post_id");
Run Code Online (Sandbox Code Playgroud)
等等...
查看JsonPath规范页面,了解有关横向JSON的其他方法的更多信息.
lub*_*lis 32
你可以使用Google Gson.
使用此库,您只需要创建具有相同JSON结构的模型.然后自动填写模型.您必须将变量作为JSON键调用,或者如果要使用不同的名称,则使用@SerializedName.
对于你的例子:
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"
}
]
}
Run Code Online (Sandbox Code Playgroud)
模型:
class MyModel {
private PageInfo pageInfo;
private ArrayList<Post> posts = new ArrayList<>();
}
class PageInfo {
private String pageName;
private String pagePic;
}
class Post {
private String post_id;
@SerializedName("actor_id") // <- example SerializedName
private String actorId;
private String picOfPersonWhoPosted;
private String nameOfPersonWhoPosted;
private String message;
private String likesCount;
private ArrayList<String> comments;
private String timeOfPost;
}
Run Code Online (Sandbox Code Playgroud)
现在您可以使用Gson库进行解析:
MyModel model = gson.fromJson(jsonString, MyModel.class);
Run Code Online (Sandbox Code Playgroud)
您可以从JSON自动使用,如在线工具生成模型这个.
Md *_*kib 24
使用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
}
]
}
Run Code Online (Sandbox Code Playgroud)
解析:
JsonObject object = Json.parse(input).asObject();
int orders = object.get("order").asInt();
JsonArray items = object.get("items").asArray();
Run Code Online (Sandbox Code Playgroud)
创建JSON:
JsonObject user = Json.object().add("name", "Sakib").add("age", 23);
Run Code Online (Sandbox Code Playgroud)
Maven的:
<dependency>
<groupId>com.eclipsesource.minimal-json</groupId>
<artifactId>minimal-json</artifactId>
<version>0.9.4</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
Gio*_*tta 20
我认为最佳实践应该是通过仍在进行中的官方Java JSON API.
jus*_*hey 19
下面的示例演示如何读取问题中的文本,表示为"jsonText"变量.此解决方案使用Java EE7 javax.json API(在其他一些答案中提到).我将其作为单独答案添加的原因是以下代码显示了如何实际访问问题中显示的某些值.需要实现javax.json API才能运行此代码.包含了所需的每个类的完整包,因为我不想声明"import"语句.
javax.json.JsonReader jr =
javax.json.Json.createReader(new StringReader(jsonText));
javax.json.JsonObject jo = jr.readObject();
//Read the page info.
javax.json.JsonObject pageInfo = jo.getJsonObject("pageInfo");
System.out.println(pageInfo.getString("pageName"));
//Read the posts.
javax.json.JsonArray posts = jo.getJsonArray("posts");
//Read the first post.
javax.json.JsonObject post = posts.getJsonObject(0);
//Read the post_id field.
String postId = post.getString("post_id");
Run Code Online (Sandbox Code Playgroud)
现在,在任何人拒绝使用GSON,org.json,Jackson或任何其他可用的第三方框架之前,这是一个解决所提供文本的"必需代码"的示例.我很清楚,JDK 9没有考虑遵守当前的标准JSR 353,因此JSR 353规范应该与任何其他第三方JSON处理实现一样对待.
oto*_*let 17
由于没有人提及它,这里是使用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));
}
Run Code Online (Sandbox Code Playgroud)
性能比较
我写了JSON内容,包含三个分别为20,20和100个元素的数组.我只想从第三个数组中获取100个元素.我使用以下JavaScript函数来解析并获取我的条目.
var fun = function(raw) {JSON.parse(raw).entries};
Run Code Online (Sandbox Code Playgroud)
使用Nashorn运行呼叫一百万次需要7.5~7.8秒
(JSObject) invocable.invokeFunction("fun", json);
Run Code Online (Sandbox Code Playgroud)
org.json需要20~21秒
new JSONObject(JSON).getJSONArray("entries");
Run Code Online (Sandbox Code Playgroud)
杰克逊需要6.5~7秒
mapper.readValue(JSON, Entries.class).getEntries();
Run Code Online (Sandbox Code Playgroud)
在这种情况下,杰克逊比Nashorn表现得更好,Nashorn比org.json表现得更好.Nashorn API比org.json或Jackson更难使用.根据您的要求,Jackson和Nashorn都可以成为可行的解决方案.
bra*_*hy1 14
这让我很轻松.您只需将StringJSON保存到默认org.json包中的JSONObject的构造函数即可.
JSONArray rootOfPage = new JSONArray(JSONString);
Run Code Online (Sandbox Code Playgroud)
完成.滴麦克风.这也适用JSONObjects.之后,您可以查看Objects使用get()对象上的方法的层次结构.
fab*_*ien 12
Java中有许多JSON库.
最臭名昭着的是:Jackson,GSON,Genson,FastJson和org.json.
选择任何库时,通常需要考虑三件事:
特别是对于JSON库(以及任何序列化/反序列化库),数据绑定通常也很有用,因为它不需要编写样板代码来打包/解压缩数据.
对于1,请参阅此基准:https://github.com/fabienrenaud/java-json-benchmark我使用JMH比较(jackson,gson,genson,fastjson,org.json,jsonp)使用流的序列化程序和反序列化程序的性能和数据绑定API.对于2,您可以在Internet上找到大量示例.上面的基准测试也可以用作示例的来源......
快速取消基准测试:Jackson比org.json好5到6倍,比GSON好两倍多.
对于您的特定示例,以下代码使用jackson解码您的json:
public class MyObj {
private PageInfo pageInfo;
private List<Post> posts;
static final class PageInfo {
private String pageName;
private String pagePic;
}
static final class Post {
private String post_id;
@JsonProperty("actor_id");
private String actorId;
@JsonProperty("picOfPersonWhoPosted")
private String pictureOfPoster;
@JsonProperty("nameOfPersonWhoPosted")
private String nameOfPoster;
private String likesCount;
private List<String> comments;
private String timeOfPost;
}
private static final ObjectMapper JACKSON = new ObjectMapper();
public static void main(String[] args) throws IOException {
MyObj o = JACKSON.readValue(args[0], MyObj.class); // assumes args[0] contains your json payload provided in your question.
}
}
Run Code Online (Sandbox Code Playgroud)
如果您有任何疑问,请告诉我.
Via*_*nin 10
除了其他答案之外,我还建议使用这个在线开源服务jsonschema2pojo.org,以便从json或json架构为GSON,Jackson 1.x或Jackson 2.x快速生成Java类.例如,如果您有:
{
"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
}
]
}
Run Code Online (Sandbox Code Playgroud)
该jsonschema2pojo.org为GSON产生:
@Generated("org.jsonschema2pojo")
public class Container {
@SerializedName("pageInfo")
@Expose
public PageInfo pageInfo;
@SerializedName("posts")
@Expose
public List<Post> posts = new ArrayList<Post>();
}
@Generated("org.jsonschema2pojo")
public class PageInfo {
@SerializedName("pageName")
@Expose
public String pageName;
@SerializedName("pagePic")
@Expose
public String pagePic;
}
@Generated("org.jsonschema2pojo")
public class Post {
@SerializedName("post_id")
@Expose
public String postId;
@SerializedName("actor_id")
@Expose
public long actorId;
@SerializedName("picOfPersonWhoPosted")
@Expose
public String picOfPersonWhoPosted;
@SerializedName("nameOfPersonWhoPosted")
@Expose
public String nameOfPersonWhoPosted;
@SerializedName("message")
@Expose
public String message;
@SerializedName("likesCount")
@Expose
public long likesCount;
@SerializedName("comments")
@Expose
public List<Object> comments = new ArrayList<Object>();
@SerializedName("timeOfPost")
@Expose
public long timeOfPost;
}
Run Code Online (Sandbox Code Playgroud)
如果你有一些表示JSON字符串(jsonString)的Java类(比如Message),你可以使用Jackson JSON库:
Message message= new ObjectMapper().readValue(jsonString, Message.class);
Run Code Online (Sandbox Code Playgroud)
从消息对象中,您可以获取其任何属性.
小智 9
有许多开源库可用于将JSON内容解析为对象或仅读取JSON值.您的要求只是读取值并将其解析为自定义对象.所以org.json库就足够了.
使用org.json库来解析它并创建JsonObject:
JSONObject jsonObj = new JSONObject(<jsonStr>);
Run Code Online (Sandbox Code Playgroud)
现在,使用此对象来获取您的值:
String id = jsonObj.getString("pageInfo");
Run Code Online (Sandbox Code Playgroud)
你可以在这里看到一个完整的例子:
小智 8
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
`
小智 7
请执行以下操作:
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(contentString);
String product = (String) jsonObject.get("productId");
Run Code Online (Sandbox Code Playgroud)
阅读以下博客文章,Java JSON。
这篇文章有点老了,但我仍然想回答您的问题。
第1步:创建数据的POJO类。
步骤2:现在使用JSON创建一个对象。
Employee employee = null;
ObjectMapper mapper = new ObjectMapper();
try{
employee = mapper.readValue(newFile("/home/sumit/employee.json"), Employee.class);
}
catch (JsonGenerationException e){
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
有关更多参考,请参考以下链接。
我有这样的 JSON:
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
}
}
Run Code Online (Sandbox Code Playgroud)
Java类
class PageInfo {
private String pageName;
private String pagePic;
// Getters and setters
}
Run Code Online (Sandbox Code Playgroud)
用于将此 JSON 转换为 Java 类的代码。
PageInfo pageInfo = JsonPath.parse(jsonString).read("$.pageInfo", PageInfo.class);
Run Code Online (Sandbox Code Playgroud)
梅文
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
您可以使用Gson库来解析JSON字符串.
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonAsString, JsonObject.class);
String pageName = jsonObject.getAsJsonObject("pageInfo").get("pageName").getAsString();
String pagePic = jsonObject.getAsJsonObject("pageInfo").get("pagePic").getAsString();
String postId = jsonObject.getAsJsonArray("posts").get(0).getAsJsonObject().get("post_id").getAsString();
Run Code Online (Sandbox Code Playgroud)
你也可以循环遍历"posts"数组,如下所示:
JsonArray posts = jsonObject.getAsJsonArray("posts");
for (JsonElement post : posts) {
String postId = post.getAsJsonObject().get("post_id").getAsString();
//do something
}
Run Code Online (Sandbox Code Playgroud)
小智 5
{
"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
}
Run Code Online (Sandbox Code Playgroud)
此页面上的热门答案使用了过于简单的示例,例如具有一个属性的对象(例如 {name: value})。我认为这个仍然简单但现实生活中的例子可以帮助某人。
这是 Google Translate API 返回的 JSON:
{
"data":
{
"translations":
[
{
"translatedText": "Arbeit"
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
我想使用 Google 的 Gson 检索“translatedText”属性的值,例如“Arbeit”。
两种可能的方法:
仅检索一个所需的属性
String json = callToTranslateApi("work", "de");
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
return jsonObject.get("data").getAsJsonObject()
.get("translations").getAsJsonArray()
.get(0).getAsJsonObject()
.get("translatedText").getAsString();
Run Code Online (Sandbox Code Playgroud)
从 JSON 创建 Java 对象
class ApiResponse {
Data data;
class Data {
Translation[] translations;
class Translation {
String translatedText;
}
}
}
Run Code Online (Sandbox Code Playgroud)
...
Gson g = new Gson();
String json =callToTranslateApi("work", "de");
ApiResponse response = g.fromJson(json, ApiResponse.class);
return response.data.translations[0].translatedText;
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用Jayway JsonPath。下面是一个包含源代码、pom 详细信息和良好文档的 GitHub 链接。
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>
Run Code Online (Sandbox Code Playgroud)
第 2 步:请将您的输入 JSON 保存为此示例的文件。就我而言,我将您的 JSON 保存为 sampleJson.txt。请注意,您错过了 pageInfo 和帖子之间的逗号。
第 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();
Run Code Online (Sandbox Code Playgroud)
第 4 步:使用 jayway JSON 解析器解析您的 JSON 字符串。
Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonInput);
Run Code Online (Sandbox Code Playgroud)
第 5 步:阅读如下详细信息。
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);
Run Code Online (Sandbox Code Playgroud)
输出将是:
$.pageInfo.pageName = abc
$.pageInfo.pagePic = http://example.com/content.jpg
$.posts[0].post_id = 123456789012_123456789012
Run Code Online (Sandbox Code Playgroud)
首先,您需要选择一个实现库来执行此操作。
所述用于处理JSON(JSR 353)的Java API提供便携式API来解析,生成,变换,并使用对象模型和流式API查询JSON。
该参考实现是在这里:https://jsonp.java.net/
在这里您可以找到JSR 353的实现列表:
而为了帮助您决定......我发现这篇文章还有:
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-杰克逊/
希望能帮助到你!
| 归档时间: |
|
| 查看次数: |
1538921 次 |
| 最近记录: |