如何parsingJSON

我有以下JSON文本,我需要parsing,以获得pageNamepagePicpost_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" } ] } 

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"); ...... } 

您可能会发现更多的例子: 在Java中parsingJSON

可下载的jar: http : //mvnrepository.com/artifact/org.json/json

为了这个例子,假设你有一个只有一个name Person类。

 private class Person { public String name; public Person(String name) { this.name = name; } } 

Google GSON ( Maven )

我个人最喜欢的伟大的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"} 

更新

如果你想获得一个单一的属性,你也可以使用Google库轻松完成:

 JsonObject jsonObject = new JsonParser().parse("{\"name\": \"John\"}").getAsJsonObject(); System.out.println(jsonObject.get("name").getAsString()); //John 

Org.JSON ( Maven )

如果你不需要对象反序列化,只需要获得一个属性,你可以尝试org.json( 或者看上面的GSON例子!

 JSONObject obj = new JSONObject("{\"name\": \"John\"}"); System.out.println(obj.getString("name")); //John 

jackson ( Maven )

 ObjectMapper mapper = new ObjectMapper(); Person user = mapper.readValue("{\"name\": \"John\"}", Person.class); System.out.println(user.name); //John 
  1. 如果您想从JSON创buildJAVA对象,反之亦然,请使用GSON或JACKSON第三方JAR等。

     //from object to JSON Gson gson = new Gson(); gson.toJson(yourObject); // from JSON to object yourObject o = gson.fromJson(JSONString,yourObject.class); 
  2. 但是,如果只想分析JSONstring并获取一些值(或者从头开始创buildJSONstring以通过线路发送),那么只需使用包含JsonReader,JsonArray,JsonObject等的JaveEE Jar即可。您可能希望下载该实现规格像javax.json。 有了这两个jar子,我可以parsingJSON并使用这些值。

    这些API实际上遵循XML的DOM / SAXparsing模型。

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

quick-jsonparsing器非常简单,灵活,非常快速且可定制。 尝试一下

特征:

  • 符合JSON规范(RFC4627)
  • 高性能的JSONparsing器
  • 支持灵活/可configuration的分析方法
  • 任何JSON层次结构的键/值对的可configurationvalidation
  • 易于使用#非常小的占地面积
  • 提高开发人员的便利性,便于追踪exception
  • 可插入的自定义validation支持 – 键/值可以通过在遇到时configuration自定义validation器进行validation
  • validation和不validationparsing器支持
  • 支持使用quick-JSONvalidationparsing器的两种types的configuration(JSON / XML)
  • 需要JDK 1.5
  • 不依赖于外部库
  • 通过对象序列化支持JSON生成
  • 支持parsing过程中的集合typesselect

它可以像这样使用:

 JsonParserFactory factory=JsonParserFactory.getInstance(); JSONParser parser=factory.newJsonParser(); Map jsonMap=parser.parseJson(jsonString); 

几乎所有给出的答案都需要在访问感兴趣的属性中的值之前将JSON完全反序列化为Java对象。 另一种不使用此路线的方法是使用JsonPATH ,它类似于JSON的XPath,并允许遍历JSON对象。

这是一个规范,JayWay的优秀人员已经为这个规范创build了一个Java实现,你可以在这里find: https : //github.com/jayway/JsonPath

所以基本上使用它,将其添加到您的项目,例如:

 <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>${version}</version> </dependency> 

并使用:

 String pageName = JsonPath.read(yourJsonString, "$.pageInfo.pageName"); String pagePic = JsonPath.read(yourJsonString, "$.pageInfo.pagePic"); String post_id = JsonPath.read(yourJsonString, "$.pagePosts[0].post_id"); 

等等…

检查JsonPath规范页面以获取有关横向JSON的其他方法的更多信息。

A – 说明

您可以使用Jackson库将JSONstring绑定到POJOPlain Old Java Object )实例中。 POJO只是一个只有私有字段和公共getter / setter方法的类。 Jackson将遍历方法(使用reflection ),并将JSON对象映射到POJO实例中,因为该类的字段名称适合JSON对象的字段名称。

在你的JSON对象中,它实际上是一个复合对象,主对象由两个子对象组成。 所以,我们的POJO类应该有相同的层次结构。 我将把整个JSON对象称为Page对象。 页面对象由一个PageInfo对象和一个Post对象数组组成。

所以我们必须创build三个不同的POJO类

  • Page Class, PageInfo类和Post Instance数组的组合
  • PageInfo
  • post

我唯一使用的包是Jackson ObjectMapper,我们所做的是绑定数据;

 com.fasterxml.jackson.databind.ObjectMapper 

所需的依赖关系,jar文件如下所示;

  • jackson核心2.5.1.jar
  • jackson-数据绑定- 2.5.1.jar
  • jackson的注解- 2.5.0.jar

这是所需的代码;

B – 主要POJO类别:

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

C – 子POJO类:PageInfo

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

D – 儿童POJO课程:职位

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

电子样本JSON文件:sampleJSONFile.json

我刚才复制你的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" } ] } 

F – 演示代码

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

G – 演示输出

 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 

你可以使用谷歌Gson

使用这个库只需要创build一个具有相同json结构的模型。 然后模型自动填充。你必须调用你的variables作为你的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" } ] 

}

模型:

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

现在你可以使用Gson库parsing:

 MyModel model = gson.fromJson(jsonString, MyModel.class); 

您可以使用这样的在线工具自动从json生成模型

使用非常快速和易于使用的最小JSON 。 你可以从String obj和Streamparsing。 示例数据:

 { "order": 4711, "items": [ { "name": "NE555 Timer IC", "cat-id": "645723", "quantity": 10, }, { "name": "LM358N OpAmp IC", "cat-id": "764525", "quantity": 2 } ] } 

parsing:

 JsonObject object = Json.parse(input).asObject(); int orders = object.get("order").asInt(); JsonArray items = object.get("items").asArray(); 

创buildJson:

 JsonObject user = Json.object().add("name", "Sakib").add("age", 23); 

Maven:

 <dependency> <groupId>com.eclipsesource.minimal-json</groupId> <artifactId>minimal-json</artifactId> <version>0.9.4</version> </dependency> 

我相信最好的做法应该是通过正在进行的官方Java JSON API 。

这让我很容易想到。 你可以传递一个持有你的JSON的String给默认的org.json包中的JSONObject的构造函数。

 JSONArray rootOfPage = new JSONArray(JSONString); 

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

下面的例子展示了如何读取问题中的文本,表示为“jsonText”variables。 该解决scheme使用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"); 

现在,在任何人走之前,由于没有使用GSON,org.json,Jackson或任何其他可用的第三方框架,所以这个答案就是一个例子,它是parsing提供的文本的“必需的代码”的例子。 我清楚地知道遵守当前的标准JSR 353并没有考虑JDK 9 ,所以JSR 353规范应该和其他任何第三方的JSON处理实现一样。

如果您有一些表示JSONstring(jsonString)的Java类(如Message),则可以使用Jackson JSON库:

 Message message= new ObjectMapper().readValue(jsonString, Message.class); 

并从消息对象中,您可以获取其任何属性。

除了其他答案外,我推荐这个在线开源服务jsonschema2pojo.org,用于从GSON,Jackson 1.x或Jackson 2.x快速生成json或json模式的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 } ] } 

GSON的jsonschema2pojo.org生成:

 @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; } 

Java中有许多JSON库可用。

最臭名昭着的是Jackson,GSON,Genson,FastJson和org.json。

通常有三件事情需要考虑select任何图书馆:

  1. 性能
  2. 易于使用(代码编写简单,易于阅读) – 符合function。
  3. 对于移动应用程序:依赖/ jar大小

特别是对于JSON库(以及任何序列化/反序列化库),数据绑定通常也是有趣的,因为它不需要编写样板代码来打包/解包数据。

对于1,看到这个基准: https : //github.com/fabienrenaud/java-json-benchmark我使用JMH比较(jackson,gson,genson,fastjson,org.json,jsonp)性能的串行器和反串行器使用stream和数据绑定API。 2,你可以在互联网上find很多例子。 上面的基准也可以作为例子的来源…

基准testing: 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. } } 

如果您有任何问题,请告诉我。

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

`

请做这样的事情:

 JSONParser jsonParser = new JSONParser(); JSONObject obj = (JSONObject) jsonParser.parse(contentString); String product = (String) jsonObject.get("productId"); 
 { "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 } 

由于没有人提到它,所以这里是使用Nashorn (Java 8的Javascript Runtime部分)的解决scheme的开始。

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

性能对比

我写了一个包含3个数组的20,20和100个元素的json。 我只想从第三个数组中获得100个元素。 我使用下面的js函数来parsing和获取我的input。

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

jackson需要6.5〜7“

 mapper.readValue(JSON, Entries.class).getEntries(); 

在这种情况下,jackson比Nashornperformance得更好,performance比org.json好得多。 Nashorn API比org.json或者Jackson更难使用。 根据您的要求,Jackson和Nashorn都可以成为可行的解决scheme。

有许多开源库存在parsingJSON对象或只是读取JSON值。 您的要求只是读取值并将其parsing为自定义对象。 所以org.json库就足够了。

使用org.json库来parsing它并创buildJsonObject:

 JSONObject jsonObj = new JSONObject(<jsonStr>); 

现在,使用这个对象来获取你的值:

 String id = jsonObj.getString("pageInfo"); 

你可以在这里看到完整的例子:

如何在Java中parsingJson

您可以使用Gson库来parsingJSONstring。

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

您也可以循环遍历“posts”数组,如下所示:

 JsonArray posts = jsonObject.getAsJsonArray("posts"); for (JsonElement post : posts) { String postId = post.getAsJsonObject().get("post_id").getAsString(); //do something } 

阅读下面的Java博客json

这个post有点老,但我仍然想回答你的问题

第1步:创build一个pojo类的数据。

第2步:现在使用json创build一个对象。

 Employee employee = null; ObjectMapper mapper = new ObjectMapper(); try{ employee = mapper.readValue(newFile("/home/sumit/employee.json"),Employee.class); } catch (JsonGenerationException e){ e.printStackTrace(); } 

有关更多参考,请参阅以下链接

谢谢

你可以使用Jayway JsonPath 。 下面是github链接源代码,pom的详细信息和良好的文档。

https://github.com/jayway/JsonPath

请按照下面的步骤。

第1步 :使用maven或下载jar文件在您的类path中添加jayway jsonpath依赖项并手动添加它。

 <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>2.2.0</version> </dependency> 

第2步 :请将您的inputjson保存为本示例的文件。 在我的情况下,我把你的json保存为sampleJson.txt。 请注意,您错过了pageInfo和post之间的逗号

第三步 :使用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(); 

第4步 :使用jayway jsonparsing器parsingjsonstring。

 Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonInput); 

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

输出将是

 $.pageInfo.pageName = abc $.pageInfo.pagePic = http://example.com/content.jpg $.posts[0].post_id = 123456789012_123456789012 

我有JSON喜欢。

 { "pageInfo": { "pageName": "abc", "pagePic": "http://example.com/content.jpg" } } 

Java类

 class PageInfo { private String pageName; private String pagePic; //getters and setters } 

将此json转换为Java类的代码。

  PageInfo pageInfo = JsonPath.parse(jsonString).read("$.pageInfo", PageInfo.class); 

Maven的

 <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <version>2.2.0</version> </dependency> 

Top answers on this page use too simple examples like object with one property (eg {name: value}). I think that still simple but real life example can help someone.

So this is the JSON returned by Google Translate API:

 { "data": { "translations": [ { "translatedText": "Arbeit" } ] } } 

I want to retrieve the value of "translatedText" attribute eg "Arbeit" using Google's Gson.

Two possible approaches:

  1. Retrieve just one needed attribute

     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(); 
  2. Create Java object from JSON

     class ApiResponse { Data data; class Data { Translation[] translations; class Translation { String translatedText; } } } 

      Gson g = new Gson(); String json =callToTranslateApi("work", "de"); ApiResponse response = g.fromJson(json, ApiResponse.class); return response.data.translations[0].translatedText; 

First you need to select an implementation library to do that.

The Java API for JSON Processing (JSR 353) provides portable APIs to parse, generate, transform, and query JSON using object model and streaming APIs.

The reference implementation is here: https://jsonp.java.net/

Here you can find a list of implementations of JSR 353:

What are the API that does implement JSR-353 (JSON)

And to help you decide … I found this article as well:

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

If you go for Jackson, here is a good article about conversion between JSON to/from Java using Jackson: https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

希望它有帮助!

You can use JsonNode for a structured tree representation of your Json string, it's part of the rock solid jackson library ( https://github.com/FasterXML/jackson ) which is omnipresent

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

We can use the JSONObject class to convert json string to JSON object, and to iterate over the json object.Use the following code.

 JSONObject jObj = new JSONObject(contents.trim()); Iterator<?> keys = jObj.keys(); while( keys.hasNext() ) { String key = (String)keys.next(); if ( jObj.get(key) instanceof JSONObject ) { System.out.println(jObj.getString(String key)); } } 

As @Gioele Costa asked before and it was marked as duplicate i will answer here:

Suppose to have this response from backend

 {"OK":[{"tavolo":"1","pizza":"magherita","quantita":"12","note":"nothing"},{"tavolo":"1","pizza":"4formaggi","quantita":"1","note":"nothing"}],"success":1} 

Following a backend – frontend and json parser utility

 $result = mysql_query(your query); if (mysql_num_rows($result) > 0) { $response["OK"] = array(); while ($row = mysql_fetch_array($result)) { // temp user array $product = array(); $product["tavolo"] = $row["tavolo"]; $product["pizza"] = $row["pizza"]; $product["quantita"] = $row["quantita"]; $product["note"] = $row["note"]; // push single product into final response array array_push($response["OK"], $product); } // success $response["success"] = 1; // echoing JSON response echo json_encode($response); } 

I used AsyncTask to implement the software client side

 //your activity.. final String url_all_products = "yoururl.something"; // JSON Node names final String TAG_SUCCESS = "success"; //Row is your bean ArrayList<Row> productsList; // products JSONArray JSONArray products = null; JSONParser jParser = new JSONParser(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new LoadAllProducts().execute(); } /** * Background Async Task * */ class LoadAllProducts extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { // do something } protected String doInBackground(String... args) { JSONObject json = jParser.makeHttpRequest(url_all_products, "GET"); try { success = json.getInt(TAG_SUCCESS); if (success == 1) { products = json.getJSONArray("OK"); productsList = new ArrayList<Row>(); // looping through All Products for (int i = 0; i < products.length(); i++) { JSONObject c = products.getJSONObject(i); Row r = new Row(); r.setDescription(c.getString("tavolo")); r.setLat(c.getString("pizza")); r.setLon(c.getString("quantita")); r.setGame_sequence(c.getString("note")); productsList.add(r); } }else {/*do something*/} } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // do something } } } } 

JSONParser class ( note Apache Http Client is not supported anymore )

 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method) { // Making HTTP request try { // check for request method if("POST".equals(method)){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if("GET".equals(method)){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); json = sb.toString(); } catch (Exception e) { e.printStackTrace(); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { e.printStackTrace(); } return jObj; } }