How to parse JSON in Java
I have the following JSON text. How can I parse it to get pageName, pagePic, post_id, etc.?
{
"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 json parsing
|
show 4 more comments
I have the following JSON text. How can I parse it to get pageName, pagePic, post_id, etc.?
{
"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 json parsing
6
java's built in JSON libraries are the quickets way to do so, but in my experience GSON is the best library for parsing a JSON into a POJO painlessly.
– Iman Akbari
Mar 9 '16 at 11:11
58
This question really was too broad and "write the code for me" which leads to a mess of confusing and differing answers below. This question should have been closed for being too broad and the author making no effort to solve it themselves, showing no homework.
– Jayson Minard
May 18 '16 at 12:57
10
This is the first highly voted and protected question whose answers I found the most confusing
– Riyafa Abdul Hameed
Jun 21 '17 at 6:48
6
@JaysonMinard agreed. Asked for mod intervention. This should be closed really. I initially assumed (wrongly) I couldn't do so while the question was protected, so I unprotected it and did my thing. Re-protected it now to prevent low rep answers and such like, while waiting for a mod.
– Mena
Jan 31 '18 at 16:59
5
This question is being discussed on Meta.
– Mark Amery
Feb 5 '18 at 12:34
|
show 4 more comments
I have the following JSON text. How can I parse it to get pageName, pagePic, post_id, etc.?
{
"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 json parsing
I have the following JSON text. How can I parse it to get pageName, pagePic, post_id, etc.?
{
"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 json parsing
java json parsing
edited Feb 5 '18 at 12:52
Mark Amery
62.7k31250296
62.7k31250296
asked Apr 7 '10 at 9:00
Muhammad Maqsoodur RehmanMuhammad Maqsoodur Rehman
13k3373114
13k3373114
6
java's built in JSON libraries are the quickets way to do so, but in my experience GSON is the best library for parsing a JSON into a POJO painlessly.
– Iman Akbari
Mar 9 '16 at 11:11
58
This question really was too broad and "write the code for me" which leads to a mess of confusing and differing answers below. This question should have been closed for being too broad and the author making no effort to solve it themselves, showing no homework.
– Jayson Minard
May 18 '16 at 12:57
10
This is the first highly voted and protected question whose answers I found the most confusing
– Riyafa Abdul Hameed
Jun 21 '17 at 6:48
6
@JaysonMinard agreed. Asked for mod intervention. This should be closed really. I initially assumed (wrongly) I couldn't do so while the question was protected, so I unprotected it and did my thing. Re-protected it now to prevent low rep answers and such like, while waiting for a mod.
– Mena
Jan 31 '18 at 16:59
5
This question is being discussed on Meta.
– Mark Amery
Feb 5 '18 at 12:34
|
show 4 more comments
6
java's built in JSON libraries are the quickets way to do so, but in my experience GSON is the best library for parsing a JSON into a POJO painlessly.
– Iman Akbari
Mar 9 '16 at 11:11
58
This question really was too broad and "write the code for me" which leads to a mess of confusing and differing answers below. This question should have been closed for being too broad and the author making no effort to solve it themselves, showing no homework.
– Jayson Minard
May 18 '16 at 12:57
10
This is the first highly voted and protected question whose answers I found the most confusing
– Riyafa Abdul Hameed
Jun 21 '17 at 6:48
6
@JaysonMinard agreed. Asked for mod intervention. This should be closed really. I initially assumed (wrongly) I couldn't do so while the question was protected, so I unprotected it and did my thing. Re-protected it now to prevent low rep answers and such like, while waiting for a mod.
– Mena
Jan 31 '18 at 16:59
5
This question is being discussed on Meta.
– Mark Amery
Feb 5 '18 at 12:34
6
6
java's built in JSON libraries are the quickets way to do so, but in my experience GSON is the best library for parsing a JSON into a POJO painlessly.
– Iman Akbari
Mar 9 '16 at 11:11
java's built in JSON libraries are the quickets way to do so, but in my experience GSON is the best library for parsing a JSON into a POJO painlessly.
– Iman Akbari
Mar 9 '16 at 11:11
58
58
This question really was too broad and "write the code for me" which leads to a mess of confusing and differing answers below. This question should have been closed for being too broad and the author making no effort to solve it themselves, showing no homework.
– Jayson Minard
May 18 '16 at 12:57
This question really was too broad and "write the code for me" which leads to a mess of confusing and differing answers below. This question should have been closed for being too broad and the author making no effort to solve it themselves, showing no homework.
– Jayson Minard
May 18 '16 at 12:57
10
10
This is the first highly voted and protected question whose answers I found the most confusing
– Riyafa Abdul Hameed
Jun 21 '17 at 6:48
This is the first highly voted and protected question whose answers I found the most confusing
– Riyafa Abdul Hameed
Jun 21 '17 at 6:48
6
6
@JaysonMinard agreed. Asked for mod intervention. This should be closed really. I initially assumed (wrongly) I couldn't do so while the question was protected, so I unprotected it and did my thing. Re-protected it now to prevent low rep answers and such like, while waiting for a mod.
– Mena
Jan 31 '18 at 16:59
@JaysonMinard agreed. Asked for mod intervention. This should be closed really. I initially assumed (wrongly) I couldn't do so while the question was protected, so I unprotected it and did my thing. Re-protected it now to prevent low rep answers and such like, while waiting for a mod.
– Mena
Jan 31 '18 at 16:59
5
5
This question is being discussed on Meta.
– Mark Amery
Feb 5 '18 at 12:34
This question is being discussed on Meta.
– Mark Amery
Feb 5 '18 at 12:34
|
show 4 more comments
31 Answers
31
active
oldest
votes
1 2
next
The org.json library is easy to use. Example code below:
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");
......
}
You may find more examples from: Parse JSON in Java
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
10
I agree with @StaxMan. I just tried org.json and it's horribly cumbersome. It really doesn't play with with standard Java Collection types, for example.
– Ken Williams
Nov 12 '14 at 16:55
7
@StaxMan I would chooseorg.jsonover other libraries for simple JSON parsing without even looking. It is the reference library that Douglas Crockford (the JSON discoverer) created.
– Omar Al-Ithawi
Nov 17 '15 at 15:49
16
@OmarIthawi that is just silly. It's a proof-of-concept with awkward API, inefficient implementation. I think it is better to consider libraries on their own merits, instead of trying to deduce quality out of its authors visibility -- Doug has achieved many things, but that does not really change qualities of the particular lib. 10 years ago it was the only game in town, but since then there has been much positive progress. It's like Struts of json libs.
– StaxMan
Nov 19 '15 at 18:54
8
org.json is amongst the worst json libraries. One should look at the feature set and performance of available json libraries before choosing. Here is a benchmark I did comparing jackson, gson, org.json, genson using JMH: github.com/fabienrenaud/java-json-benchmark. jackson is the clear winner here.
– fabien
Jun 27 '16 at 20:53
3
The License doesn't include any commonly used Open Source licensing, and it also holds copyrights.
– Christian Vielma
Aug 11 '16 at 14:43
|
show 6 more comments
For the sake of the example lets assume you have a class Person with just a name.
private class Person {
public String name;
public Person(String name) {
this.name = name;
}
}
Google GSON (Maven)
My personal favourite as to the great JSON serialisation / de-serialisation of objects.
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:
JsonObject jsonObject = new JsonParser().parse("{"name": "John"}").getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString()); //John
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!)
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
13
Good answer. One suggestion for minor improvement: both GSON and Jackson also support use of JSON tree representation (for Jackson these areJsonNodes, GSON has something similar). Might be good to show snippets, since that is similar to the only way org.json offers.
– StaxMan
Oct 6 '15 at 18:05
Two other libraries worth mentioning (in the interest of completeness): json-simple and Oracle's JSONP
– jake stayman
Apr 1 '16 at 19:04
1
@NeonWarge, why? It seems to me that this answer assumes one has already defined a Java class that contains exactly the same fields as the JSON string, nothing less and nothing more. This is quite a strong assumption.
– Andrea Lazzarotto
Apr 9 '16 at 20:40
1
json-simple and oracle's jsonp perform terribly: github.com/fabienrenaud/java-json-benchmark For performance, choose jackson or dsljson.
– fabien
Aug 1 '16 at 1:04
GSON does not support dynamic filtering of fields on levels other than root!
– Gangnus
Aug 6 '16 at 14:02
|
show 2 more comments
If one wants to create Java object from JSON and vice versa, use GSON or JACKSON 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");
4
@nondescript If I had to guess I'd say it was downvoted because it doesn't answer the original poster's question: "What is the required code?" The answers that were upvoted provided code snippets.
– jewbix.cube
Apr 27 '15 at 21:40
4
Note: Jackson and GSON both support tree-style and/or Maps/Lists binding, so there is no need to use Java EE (javax.json) package. javax.json has little to offer beyond either Jackson or GSON.
– StaxMan
Jun 1 '15 at 23:10
I suggest adding a link to the JavaEE library.
– Basil Bourque
May 26 '18 at 6:25
add a comment |
quick-json parser is very straightforward, flexible, very fast and customizable. Try it
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
It can be used like this:
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
3
Is there a javadoc available?
– jboi
Sep 10 '13 at 11:38
20
This package cannot handle empty values when parsing. For example: ... "description":"" ... throws an Exception
– Ivan
Oct 25 '13 at 15:45
6
I've fixed this issue (and many others) in code.google.com/p/quick-json/issues/detail?id=11 I hope the author will give take the time to fix it in the official release.
– noamik
Aug 8 '14 at 12:28
8
Of listed features, nothing is unique compared to other options -- and claim of high-performance is not supported by anything; unlike for more mature libraries (Gson, Jackson, Genson, Boon) which are included in benchmarks like github.com/eishay/jvm-serializers, github.com/novoj/JavaJsonPerformanceTest or developer.com/lang/jscript/… -- I have not seen this library included in tests, or mentions of it being widely used.
– StaxMan
Oct 24 '14 at 5:12
18
This project appears to be dead and appears to be no longer hosted in the central Maven repository.
– 8bitjunkie
Nov 8 '15 at 22:16
|
show 4 more comments
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 JsonPATH which is like XPath for JSON and allows traversing of JSON objects.
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
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.
add a comment |
A - Explanation
You can use Jackson libraries, for binding JSON String into POJO (Plain Old Java Object) instances. POJO is simply a class with only private fields and public getter/setter methods. Jackson is going to traverse the methods (using reflection), and maps the JSON object into the POJO instance as the field names of the class fits to the field names of the JSON object.
In your JSON object, which is actually a composite object, the main object consists o two sub-objects. So, our POJO classes should have the same hierarchy. I'll call the whole JSON Object as Page object. Page object consist of a PageInfo object, and a Post object array.
So we have to create three different POJO classes;
Page Class, a composite of PageInfo Class and array of Post Instances
PageInfo Class
Posts Class
The only package I've used is Jackson ObjectMapper, what we do is binding data;
com.fasterxml.jackson.databind.ObjectMapper
The required dependencies, the jar files is listed below;
- jackson-core-2.5.1.jar
- jackson-databind-2.5.1.jar
- jackson-annotations-2.5.0.jar
Here is the required code;
B - Main POJO Class : Page
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 - Child POJO Class : 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 - Child POJO Class : Post
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;
}
}
E - Sample JSON File : sampleJSONFile.json
I've just copied your JSON sample into this file and put it under the project folder.
{
"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 - Demo Code
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 - Demo Output
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
add a comment |
You could use Google Gson.
Using this library you only need to create a model with the same JSON structure. Then the model is automatically filled in. You have to call your variables as your JSON keys, or use @SerializedName if you want to use different names.
For your example:
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"
}
]
}
Model:
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;
}
Now you can parse using Gson library:
MyModel model = gson.fromJson(jsonString, MyModel.class);
You can generate model from JSON automatically using online tools like this.
add a comment |
Use minimal-json which is very fast and easy to use.
You can parse from String obj and Stream.
Sample data:
{
"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();
Creating JSON:
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>
How does the pojo will look?
– Jesse
Mar 29 '17 at 15:24
For Pojo use gson. This library doesn't support.
– Sakib Sami
Mar 29 '17 at 20:01
add a comment |
I believe the best practice should be to go through the official Java JSON API which are still work in progress.
7
Since I replied, I started using Jackson and I think it's one of the best libraries out there for JSON de-serialization.
– Giovanni Botta
Sep 11 '14 at 14:26
2
Why do they re-use JSONP to mean something different than JSON with Padding?...
– Chris Wesseling
May 14 '15 at 5:53
@ChrisWesseling What do you mean?
– Giovanni Botta
May 14 '15 at 18:43
"Java API for JSON Processing (JSON-P)" is the title of the document you link to. And it confused me, because I knew JSONP to mean something else.
– Chris Wesseling
May 14 '15 at 18:48
1
@ChrisWesseling oh that is confusing. That's what they chose for the specification. However as I said, I would go straight to Jackson.
– Giovanni Botta
May 14 '15 at 18:50
|
show 1 more comment
The below example shows how to read the text in the question, represented as the "jsonText" variable. This solution uses the Java EE7 javax.json API (which is mentioned in some of the other answers). The reason I've added it as a separate answer is that the following code shows how to actually access some of the values shown in the question. An implementation of the javax.json API would be required to make this code run. The full package for each of the classes required was included as I didn't want to declare "import" statements.
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");
Now, before anyone goes and downvotes this answer because it doesn't use GSON, org.json, Jackson, or any of the other 3rd party frameworks available, it's an example of "required code" per the question to parse the provided text. I am well aware that adherence to the current standard JSR 353 was not being considered for JDK 9 and as such the JSR 353 spec should be treated the same as any other 3rd party JSON handling implementation.
add a comment |
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.
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.
10
TheJSONArraytype is not part of the J2SE JDK API and you don't say which API or third-party library provides this type.
– Bobulous
Apr 24 '15 at 22:22
2
Not that I would recommend using it, but I think this refers to the "org.json" package from json.org/java. It used to be used before good Java libraries became available, but this was years ago (2008 or before)
– StaxMan
Jun 1 '15 at 23:11
Or does brainmurphy1 mean JSONArray in Android?
– Alexander Farber
Feb 21 '18 at 13:44
add a comment |
Since nobody mentioned it yet, here is a beginning of a solution using Nashorn (JavaScript runtime part of Java 8, but deprecated in Java 11).
Solution
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));
}
Performance comparison
I wrote JSON content containing three arrays of respectively 20, 20 and 100 elements. I only want to get the 100 elements from the third array. I use the following JavaScript function to parse and get my entries.
var fun = function(raw) {JSON.parse(raw).entries};
Running the call a million times using Nashorn takes 7.5~7.8 seconds
(JSObject) invocable.invokeFunction("fun", json);
org.json takes 20~21 seconds
new JSONObject(JSON).getJSONArray("entries");
Jackson takes 6.5~7 seconds
mapper.readValue(JSON, Entries.class).getEntries();
In this case Jackson performs better than Nashorn, which performs much better than org.json.
Nashorn API is harder to use than org.json's or Jackson's. Depending on your requirements Jackson and Nashorn both can be viable solutions.
1
What is the unit """? Not inches? Is it seconds? Minutes?
– Peter Mortensen
Feb 4 '18 at 18:55
1
@PeterMortensen it means seconds. Since it seems unclear I'll change it. Thanks for the review.
– otonglet
Feb 5 '18 at 9:18
1
Unfortunately, Nashorn is deprecated in Java 11. JEP 335.
– Per Mildner
Oct 25 '18 at 13:14
add a comment |
There are many JSON libraries available in Java.
The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.
There are typically three things one should look at for choosing any library:
- Performance
- Ease of use (code is simple to write and legible) - that goes with features.
- For mobile apps: dependency/jar size
Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.
For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs.
For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...
Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.
For your particular example, the following code decodes your json with jackson:
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.
}
}
Let me know if you have any questions.
add a comment |
If you have some Java class(say Message) representing the JSON string(jsonString), you can use Jackson JSON library with:
Message message= new ObjectMapper().readValue(jsonString, Message.class);
and from message object you can fetch any of its attribute.
add a comment |
In addition to other answers, I recomend this online opensource service jsonschema2pojo.org for quick generating Java classes from json or json schema for GSON, Jackson 1.x or Jackson 2.x. For example, if you have:
{
"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
}
]
}
The jsonschema2pojo.org for GSON generated:
@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;
}
add a comment |
There are many open source libraries present to parse JSON content to an object or just to read JSON values. Your requirement is just to read values and parsing it to custom object. So org.json library is enough in your case.
Use org.json library to parse it and create JsonObject:
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values:
String id = jsonObj.getString("pageInfo");
You can see a complete example here:
How to parse JSON in Java
It seems like all your answers contain a link to that site. If it's spam, please stop. If it's not, sorry for the confusion, but I don't think that it's necessary to post a link in all your answers.
– Donald Duck
Mar 3 '17 at 12:43
1
Its tough to give an answer, where you can explain all scenarios. Like in this case, how to read json array or multiple json objects. Even If I do so, answer would be very long and person may get confuse. So I give a link where proper explanation is given, with proper example. He can chose to visit or can use only my explanation only.
– lalitbhagtani
Mar 3 '17 at 12:51
1
It appears to me that the link you have provided only demonstrates how to read JSON. Where can I find info on how to JSON as well?
– Lampros Tzanetos
Oct 27 '17 at 12:53
Sorry, but I didn't understand your question :- "on how to JSON as well"
– lalitbhagtani
Oct 31 '17 at 7:56
add a comment |
Gson is easy to learn and implement, what we need to know are following two methods
toJson() – Convert Java object to JSON format
fromJson() – Convert JSON into Java object
`
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();
}
}
}
`
For complete knowledge on Gson refer below links. github.com/google/gson/blob/master/UserGuide.md
– venkat
Feb 5 '16 at 6:24
add a comment |
You can use the Gson Library to parse the JSON string.
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();
You can also loop through the "posts" array as so:
JsonArray posts = jsonObject.getAsJsonArray("posts");
for (JsonElement post : posts) {
String postId = post.getAsJsonObject().get("post_id").getAsString();
//do something
}
add a comment |
Please do something like this:
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(contentString);
String product = (String) jsonObject.get("productId");
7
Er, which library is this?
– Stewart
Mar 19 '16 at 22:57
I think he is using org.json.simple
– Lasitha Yapa
Aug 23 '16 at 9:21
add a comment |
Top answers on this page use too simple examples like object with one property (e.g. {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 e.g. "Arbeit" using Google's Gson.
Two possible approaches:
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();
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;
add a comment |
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/
Hope it helps!
You are pointing to version 1 of Jackson library. Strongly suggest to use current version of Jackson library.
– Herbert Yu
Aug 22 '17 at 0:58
add a comment |
Read the following blog post, JSON in Java.
This post is a little bit old, but still I want to answer you question.
Step 1: Create a POJO class of your data.
Step 2: Now create a object using JSON.
Employee employee = null;
ObjectMapper mapper = new ObjectMapper();
try{
employee = mapper.readValue(newFile("/home/sumit/employee.json"), Employee.class);
}
catch (JsonGenerationException e){
e.printStackTrace();
}
For further reference you can refer to the following link.
add a comment |
You can use Jayway JsonPath. Below is a GitHub link with source code, pom details and good documentation.
https://github.com/jayway/JsonPath
Please follow the below steps.
Step 1: Add the jayway JSON path dependency in your class path using Maven or download the JAR file and manually add it.
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
Step 2: Please save your input JSON as a file for this example. In my case I saved your JSON as sampleJson.txt. Note you missed a comma between pageInfo and posts.
Step 3: Read the JSON contents from the above file using bufferedReader and save it as 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();
Step 4: Parse your JSON string using jayway JSON parser.
Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonInput);
Step 5: Read the details like below.
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);
The output will be:
$.pageInfo.pageName = abc
$.pageInfo.pagePic = http://example.com/content.jpg
$.posts[0].post_id = 123456789012_123456789012
add a comment |
{
"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
}
7
Please explain your answer as code-only answers help others far less than well documented code. See "give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime".
– Wai Ha Lee
Jul 28 '15 at 15:04
Would be good to mention this is for 'org.json' lib. However, I do not think this is a good way to do it at all being very verbose, and 'org.json' lib itself being obsolete (slow, cumbersome API). There are better choices: GSON, Jackson, Boon, Genson to use.
– StaxMan
Oct 6 '15 at 18:07
add a comment |
I have JSON like this:
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
}
}
Java class
class PageInfo {
private String pageName;
private String pagePic;
// Getters and setters
}
Code for converting this JSON to a Java class.
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>
add a comment |
One can use Apache @Model annotation to create Java model classes representing structure of JSON files and use them to access various elements in the JSON tree. Unlike other solutions this one works completely without reflection and is thus suitable for environments where reflection is impossible or comes with significant overhead.
There is a sample Maven project showing the usage. First of all it defines the structure:
@Model(className="RepositoryInfo", properties = {
@Property(name = "id", type = int.class),
@Property(name = "name", type = String.class),
@Property(name = "owner", type = Owner.class),
@Property(name = "private", type = boolean.class),
})
final class RepositoryCntrl {
@Model(className = "Owner", properties = {
@Property(name = "login", type = String.class)
})
static final class OwnerCntrl {
}
}
and then it uses the generated RepositoryInfo and Owner classes to parse the provided input stream and pick certain information up while doing that:
List<RepositoryInfo> repositories = new ArrayList<>();
try (InputStream is = initializeStream(args)) {
Models.parse(CONTEXT, RepositoryInfo.class, is, repositories);
}
System.err.println("there is " + repositories.size() + " repositories");
repositories.stream().filter((repo) -> repo != null).forEach((repo) -> {
System.err.println("repository " + repo.getName() +
" is owned by " + repo.getOwner().getLogin()
);
})
That is it! In addition to that here is a live gist showing similar example together with asynchronous network communication.
add a comment |
You can use JsonNode for a structured tree representation of your JSON string. It's part of the rock solid jackson library which is omnipresent.
ObjectMapper mapper = new ObjectMapper();
JsonNode yourObj = mapper.readTree("{"k":"v"}");
add a comment |
We can use the JSONObject class to convert a JSON string to a 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));
}
}
2
This is android only
– Ľubomír
May 5 '17 at 16:01
It's not just android: docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
– Dermot Canniffe
Sep 7 '17 at 9:47
1
@DermotCanniffe it is just Android.
– user4020527
Oct 28 '17 at 5:29
add a comment |
jsoniter (jsoniterator) is a relatively new and simple json library, designed to be simple and fast. All you need to do to deserialize json data is
JsonIterator.deserialize(jsonData, int.class);
where jsonData is a string of json data.
Check out the official website
for more information.
add a comment |
First of all this is not a valid json data.
You have to put a comma between the two json elements pageInfo and posts.
Here is the valid 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"
}
]
}
Now you may parse it using any of above described methods, or if you implement this library, then it is best.
add a comment |
1 2
next
protected by Mena Jan 31 '18 at 16:55
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
31 Answers
31
active
oldest
votes
31 Answers
31
active
oldest
votes
active
oldest
votes
active
oldest
votes
1 2
next
The org.json library is easy to use. Example code below:
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");
......
}
You may find more examples from: Parse JSON in Java
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
10
I agree with @StaxMan. I just tried org.json and it's horribly cumbersome. It really doesn't play with with standard Java Collection types, for example.
– Ken Williams
Nov 12 '14 at 16:55
7
@StaxMan I would chooseorg.jsonover other libraries for simple JSON parsing without even looking. It is the reference library that Douglas Crockford (the JSON discoverer) created.
– Omar Al-Ithawi
Nov 17 '15 at 15:49
16
@OmarIthawi that is just silly. It's a proof-of-concept with awkward API, inefficient implementation. I think it is better to consider libraries on their own merits, instead of trying to deduce quality out of its authors visibility -- Doug has achieved many things, but that does not really change qualities of the particular lib. 10 years ago it was the only game in town, but since then there has been much positive progress. It's like Struts of json libs.
– StaxMan
Nov 19 '15 at 18:54
8
org.json is amongst the worst json libraries. One should look at the feature set and performance of available json libraries before choosing. Here is a benchmark I did comparing jackson, gson, org.json, genson using JMH: github.com/fabienrenaud/java-json-benchmark. jackson is the clear winner here.
– fabien
Jun 27 '16 at 20:53
3
The License doesn't include any commonly used Open Source licensing, and it also holds copyrights.
– Christian Vielma
Aug 11 '16 at 14:43
|
show 6 more comments
The org.json library is easy to use. Example code below:
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");
......
}
You may find more examples from: Parse JSON in Java
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
10
I agree with @StaxMan. I just tried org.json and it's horribly cumbersome. It really doesn't play with with standard Java Collection types, for example.
– Ken Williams
Nov 12 '14 at 16:55
7
@StaxMan I would chooseorg.jsonover other libraries for simple JSON parsing without even looking. It is the reference library that Douglas Crockford (the JSON discoverer) created.
– Omar Al-Ithawi
Nov 17 '15 at 15:49
16
@OmarIthawi that is just silly. It's a proof-of-concept with awkward API, inefficient implementation. I think it is better to consider libraries on their own merits, instead of trying to deduce quality out of its authors visibility -- Doug has achieved many things, but that does not really change qualities of the particular lib. 10 years ago it was the only game in town, but since then there has been much positive progress. It's like Struts of json libs.
– StaxMan
Nov 19 '15 at 18:54
8
org.json is amongst the worst json libraries. One should look at the feature set and performance of available json libraries before choosing. Here is a benchmark I did comparing jackson, gson, org.json, genson using JMH: github.com/fabienrenaud/java-json-benchmark. jackson is the clear winner here.
– fabien
Jun 27 '16 at 20:53
3
The License doesn't include any commonly used Open Source licensing, and it also holds copyrights.
– Christian Vielma
Aug 11 '16 at 14:43
|
show 6 more comments
The org.json library is easy to use. Example code below:
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");
......
}
You may find more examples from: Parse JSON in Java
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
The org.json library is easy to use. Example code below:
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");
......
}
You may find more examples from: Parse JSON in Java
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
edited May 15 '18 at 10:39
Pavneet_Singh
26.7k42544
26.7k42544
answered Sep 25 '13 at 6:56
user1931858user1931858
7,3081135
7,3081135
10
I agree with @StaxMan. I just tried org.json and it's horribly cumbersome. It really doesn't play with with standard Java Collection types, for example.
– Ken Williams
Nov 12 '14 at 16:55
7
@StaxMan I would chooseorg.jsonover other libraries for simple JSON parsing without even looking. It is the reference library that Douglas Crockford (the JSON discoverer) created.
– Omar Al-Ithawi
Nov 17 '15 at 15:49
16
@OmarIthawi that is just silly. It's a proof-of-concept with awkward API, inefficient implementation. I think it is better to consider libraries on their own merits, instead of trying to deduce quality out of its authors visibility -- Doug has achieved many things, but that does not really change qualities of the particular lib. 10 years ago it was the only game in town, but since then there has been much positive progress. It's like Struts of json libs.
– StaxMan
Nov 19 '15 at 18:54
8
org.json is amongst the worst json libraries. One should look at the feature set and performance of available json libraries before choosing. Here is a benchmark I did comparing jackson, gson, org.json, genson using JMH: github.com/fabienrenaud/java-json-benchmark. jackson is the clear winner here.
– fabien
Jun 27 '16 at 20:53
3
The License doesn't include any commonly used Open Source licensing, and it also holds copyrights.
– Christian Vielma
Aug 11 '16 at 14:43
|
show 6 more comments
10
I agree with @StaxMan. I just tried org.json and it's horribly cumbersome. It really doesn't play with with standard Java Collection types, for example.
– Ken Williams
Nov 12 '14 at 16:55
7
@StaxMan I would chooseorg.jsonover other libraries for simple JSON parsing without even looking. It is the reference library that Douglas Crockford (the JSON discoverer) created.
– Omar Al-Ithawi
Nov 17 '15 at 15:49
16
@OmarIthawi that is just silly. It's a proof-of-concept with awkward API, inefficient implementation. I think it is better to consider libraries on their own merits, instead of trying to deduce quality out of its authors visibility -- Doug has achieved many things, but that does not really change qualities of the particular lib. 10 years ago it was the only game in town, but since then there has been much positive progress. It's like Struts of json libs.
– StaxMan
Nov 19 '15 at 18:54
8
org.json is amongst the worst json libraries. One should look at the feature set and performance of available json libraries before choosing. Here is a benchmark I did comparing jackson, gson, org.json, genson using JMH: github.com/fabienrenaud/java-json-benchmark. jackson is the clear winner here.
– fabien
Jun 27 '16 at 20:53
3
The License doesn't include any commonly used Open Source licensing, and it also holds copyrights.
– Christian Vielma
Aug 11 '16 at 14:43
10
10
I agree with @StaxMan. I just tried org.json and it's horribly cumbersome. It really doesn't play with with standard Java Collection types, for example.
– Ken Williams
Nov 12 '14 at 16:55
I agree with @StaxMan. I just tried org.json and it's horribly cumbersome. It really doesn't play with with standard Java Collection types, for example.
– Ken Williams
Nov 12 '14 at 16:55
7
7
@StaxMan I would choose
org.json over other libraries for simple JSON parsing without even looking. It is the reference library that Douglas Crockford (the JSON discoverer) created.– Omar Al-Ithawi
Nov 17 '15 at 15:49
@StaxMan I would choose
org.json over other libraries for simple JSON parsing without even looking. It is the reference library that Douglas Crockford (the JSON discoverer) created.– Omar Al-Ithawi
Nov 17 '15 at 15:49
16
16
@OmarIthawi that is just silly. It's a proof-of-concept with awkward API, inefficient implementation. I think it is better to consider libraries on their own merits, instead of trying to deduce quality out of its authors visibility -- Doug has achieved many things, but that does not really change qualities of the particular lib. 10 years ago it was the only game in town, but since then there has been much positive progress. It's like Struts of json libs.
– StaxMan
Nov 19 '15 at 18:54
@OmarIthawi that is just silly. It's a proof-of-concept with awkward API, inefficient implementation. I think it is better to consider libraries on their own merits, instead of trying to deduce quality out of its authors visibility -- Doug has achieved many things, but that does not really change qualities of the particular lib. 10 years ago it was the only game in town, but since then there has been much positive progress. It's like Struts of json libs.
– StaxMan
Nov 19 '15 at 18:54
8
8
org.json is amongst the worst json libraries. One should look at the feature set and performance of available json libraries before choosing. Here is a benchmark I did comparing jackson, gson, org.json, genson using JMH: github.com/fabienrenaud/java-json-benchmark. jackson is the clear winner here.
– fabien
Jun 27 '16 at 20:53
org.json is amongst the worst json libraries. One should look at the feature set and performance of available json libraries before choosing. Here is a benchmark I did comparing jackson, gson, org.json, genson using JMH: github.com/fabienrenaud/java-json-benchmark. jackson is the clear winner here.
– fabien
Jun 27 '16 at 20:53
3
3
The License doesn't include any commonly used Open Source licensing, and it also holds copyrights.
– Christian Vielma
Aug 11 '16 at 14:43
The License doesn't include any commonly used Open Source licensing, and it also holds copyrights.
– Christian Vielma
Aug 11 '16 at 14:43
|
show 6 more comments
For the sake of the example lets assume you have a class Person with just a name.
private class Person {
public String name;
public Person(String name) {
this.name = name;
}
}
Google GSON (Maven)
My personal favourite as to the great JSON serialisation / de-serialisation of objects.
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:
JsonObject jsonObject = new JsonParser().parse("{"name": "John"}").getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString()); //John
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!)
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
13
Good answer. One suggestion for minor improvement: both GSON and Jackson also support use of JSON tree representation (for Jackson these areJsonNodes, GSON has something similar). Might be good to show snippets, since that is similar to the only way org.json offers.
– StaxMan
Oct 6 '15 at 18:05
Two other libraries worth mentioning (in the interest of completeness): json-simple and Oracle's JSONP
– jake stayman
Apr 1 '16 at 19:04
1
@NeonWarge, why? It seems to me that this answer assumes one has already defined a Java class that contains exactly the same fields as the JSON string, nothing less and nothing more. This is quite a strong assumption.
– Andrea Lazzarotto
Apr 9 '16 at 20:40
1
json-simple and oracle's jsonp perform terribly: github.com/fabienrenaud/java-json-benchmark For performance, choose jackson or dsljson.
– fabien
Aug 1 '16 at 1:04
GSON does not support dynamic filtering of fields on levels other than root!
– Gangnus
Aug 6 '16 at 14:02
|
show 2 more comments
For the sake of the example lets assume you have a class Person with just a name.
private class Person {
public String name;
public Person(String name) {
this.name = name;
}
}
Google GSON (Maven)
My personal favourite as to the great JSON serialisation / de-serialisation of objects.
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:
JsonObject jsonObject = new JsonParser().parse("{"name": "John"}").getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString()); //John
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!)
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
13
Good answer. One suggestion for minor improvement: both GSON and Jackson also support use of JSON tree representation (for Jackson these areJsonNodes, GSON has something similar). Might be good to show snippets, since that is similar to the only way org.json offers.
– StaxMan
Oct 6 '15 at 18:05
Two other libraries worth mentioning (in the interest of completeness): json-simple and Oracle's JSONP
– jake stayman
Apr 1 '16 at 19:04
1
@NeonWarge, why? It seems to me that this answer assumes one has already defined a Java class that contains exactly the same fields as the JSON string, nothing less and nothing more. This is quite a strong assumption.
– Andrea Lazzarotto
Apr 9 '16 at 20:40
1
json-simple and oracle's jsonp perform terribly: github.com/fabienrenaud/java-json-benchmark For performance, choose jackson or dsljson.
– fabien
Aug 1 '16 at 1:04
GSON does not support dynamic filtering of fields on levels other than root!
– Gangnus
Aug 6 '16 at 14:02
|
show 2 more comments
For the sake of the example lets assume you have a class Person with just a name.
private class Person {
public String name;
public Person(String name) {
this.name = name;
}
}
Google GSON (Maven)
My personal favourite as to the great JSON serialisation / de-serialisation of objects.
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:
JsonObject jsonObject = new JsonParser().parse("{"name": "John"}").getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString()); //John
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!)
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
For the sake of the example lets assume you have a class Person with just a name.
private class Person {
public String name;
public Person(String name) {
this.name = name;
}
}
Google GSON (Maven)
My personal favourite as to the great JSON serialisation / de-serialisation of objects.
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:
JsonObject jsonObject = new JsonParser().parse("{"name": "John"}").getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString()); //John
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!)
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
edited Apr 1 '16 at 19:42
jake stayman
892718
892718
answered Jul 31 '15 at 9:54
SDekovSDekov
6,31911133
6,31911133
13
Good answer. One suggestion for minor improvement: both GSON and Jackson also support use of JSON tree representation (for Jackson these areJsonNodes, GSON has something similar). Might be good to show snippets, since that is similar to the only way org.json offers.
– StaxMan
Oct 6 '15 at 18:05
Two other libraries worth mentioning (in the interest of completeness): json-simple and Oracle's JSONP
– jake stayman
Apr 1 '16 at 19:04
1
@NeonWarge, why? It seems to me that this answer assumes one has already defined a Java class that contains exactly the same fields as the JSON string, nothing less and nothing more. This is quite a strong assumption.
– Andrea Lazzarotto
Apr 9 '16 at 20:40
1
json-simple and oracle's jsonp perform terribly: github.com/fabienrenaud/java-json-benchmark For performance, choose jackson or dsljson.
– fabien
Aug 1 '16 at 1:04
GSON does not support dynamic filtering of fields on levels other than root!
– Gangnus
Aug 6 '16 at 14:02
|
show 2 more comments
13
Good answer. One suggestion for minor improvement: both GSON and Jackson also support use of JSON tree representation (for Jackson these areJsonNodes, GSON has something similar). Might be good to show snippets, since that is similar to the only way org.json offers.
– StaxMan
Oct 6 '15 at 18:05
Two other libraries worth mentioning (in the interest of completeness): json-simple and Oracle's JSONP
– jake stayman
Apr 1 '16 at 19:04
1
@NeonWarge, why? It seems to me that this answer assumes one has already defined a Java class that contains exactly the same fields as the JSON string, nothing less and nothing more. This is quite a strong assumption.
– Andrea Lazzarotto
Apr 9 '16 at 20:40
1
json-simple and oracle's jsonp perform terribly: github.com/fabienrenaud/java-json-benchmark For performance, choose jackson or dsljson.
– fabien
Aug 1 '16 at 1:04
GSON does not support dynamic filtering of fields on levels other than root!
– Gangnus
Aug 6 '16 at 14:02
13
13
Good answer. One suggestion for minor improvement: both GSON and Jackson also support use of JSON tree representation (for Jackson these are
JsonNodes, GSON has something similar). Might be good to show snippets, since that is similar to the only way org.json offers.– StaxMan
Oct 6 '15 at 18:05
Good answer. One suggestion for minor improvement: both GSON and Jackson also support use of JSON tree representation (for Jackson these are
JsonNodes, GSON has something similar). Might be good to show snippets, since that is similar to the only way org.json offers.– StaxMan
Oct 6 '15 at 18:05
Two other libraries worth mentioning (in the interest of completeness): json-simple and Oracle's JSONP
– jake stayman
Apr 1 '16 at 19:04
Two other libraries worth mentioning (in the interest of completeness): json-simple and Oracle's JSONP
– jake stayman
Apr 1 '16 at 19:04
1
1
@NeonWarge, why? It seems to me that this answer assumes one has already defined a Java class that contains exactly the same fields as the JSON string, nothing less and nothing more. This is quite a strong assumption.
– Andrea Lazzarotto
Apr 9 '16 at 20:40
@NeonWarge, why? It seems to me that this answer assumes one has already defined a Java class that contains exactly the same fields as the JSON string, nothing less and nothing more. This is quite a strong assumption.
– Andrea Lazzarotto
Apr 9 '16 at 20:40
1
1
json-simple and oracle's jsonp perform terribly: github.com/fabienrenaud/java-json-benchmark For performance, choose jackson or dsljson.
– fabien
Aug 1 '16 at 1:04
json-simple and oracle's jsonp perform terribly: github.com/fabienrenaud/java-json-benchmark For performance, choose jackson or dsljson.
– fabien
Aug 1 '16 at 1:04
GSON does not support dynamic filtering of fields on levels other than root!
– Gangnus
Aug 6 '16 at 14:02
GSON does not support dynamic filtering of fields on levels other than root!
– Gangnus
Aug 6 '16 at 14:02
|
show 2 more comments
If one wants to create Java object from JSON and vice versa, use GSON or JACKSON 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");
4
@nondescript If I had to guess I'd say it was downvoted because it doesn't answer the original poster's question: "What is the required code?" The answers that were upvoted provided code snippets.
– jewbix.cube
Apr 27 '15 at 21:40
4
Note: Jackson and GSON both support tree-style and/or Maps/Lists binding, so there is no need to use Java EE (javax.json) package. javax.json has little to offer beyond either Jackson or GSON.
– StaxMan
Jun 1 '15 at 23:10
I suggest adding a link to the JavaEE library.
– Basil Bourque
May 26 '18 at 6:25
add a comment |
If one wants to create Java object from JSON and vice versa, use GSON or JACKSON 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");
4
@nondescript If I had to guess I'd say it was downvoted because it doesn't answer the original poster's question: "What is the required code?" The answers that were upvoted provided code snippets.
– jewbix.cube
Apr 27 '15 at 21:40
4
Note: Jackson and GSON both support tree-style and/or Maps/Lists binding, so there is no need to use Java EE (javax.json) package. javax.json has little to offer beyond either Jackson or GSON.
– StaxMan
Jun 1 '15 at 23:10
I suggest adding a link to the JavaEE library.
– Basil Bourque
May 26 '18 at 6:25
add a comment |
If one wants to create Java object from JSON and vice versa, use GSON or JACKSON 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");
If one wants to create Java object from JSON and vice versa, use GSON or JACKSON 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");
edited Aug 24 '18 at 23:45
Koray Tugay
9,04126116224
9,04126116224
answered Feb 18 '15 at 23:34
nondescriptnondescript
1,049815
1,049815
4
@nondescript If I had to guess I'd say it was downvoted because it doesn't answer the original poster's question: "What is the required code?" The answers that were upvoted provided code snippets.
– jewbix.cube
Apr 27 '15 at 21:40
4
Note: Jackson and GSON both support tree-style and/or Maps/Lists binding, so there is no need to use Java EE (javax.json) package. javax.json has little to offer beyond either Jackson or GSON.
– StaxMan
Jun 1 '15 at 23:10
I suggest adding a link to the JavaEE library.
– Basil Bourque
May 26 '18 at 6:25
add a comment |
4
@nondescript If I had to guess I'd say it was downvoted because it doesn't answer the original poster's question: "What is the required code?" The answers that were upvoted provided code snippets.
– jewbix.cube
Apr 27 '15 at 21:40
4
Note: Jackson and GSON both support tree-style and/or Maps/Lists binding, so there is no need to use Java EE (javax.json) package. javax.json has little to offer beyond either Jackson or GSON.
– StaxMan
Jun 1 '15 at 23:10
I suggest adding a link to the JavaEE library.
– Basil Bourque
May 26 '18 at 6:25
4
4
@nondescript If I had to guess I'd say it was downvoted because it doesn't answer the original poster's question: "What is the required code?" The answers that were upvoted provided code snippets.
– jewbix.cube
Apr 27 '15 at 21:40
@nondescript If I had to guess I'd say it was downvoted because it doesn't answer the original poster's question: "What is the required code?" The answers that were upvoted provided code snippets.
– jewbix.cube
Apr 27 '15 at 21:40
4
4
Note: Jackson and GSON both support tree-style and/or Maps/Lists binding, so there is no need to use Java EE (javax.json) package. javax.json has little to offer beyond either Jackson or GSON.
– StaxMan
Jun 1 '15 at 23:10
Note: Jackson and GSON both support tree-style and/or Maps/Lists binding, so there is no need to use Java EE (javax.json) package. javax.json has little to offer beyond either Jackson or GSON.
– StaxMan
Jun 1 '15 at 23:10
I suggest adding a link to the JavaEE library.
– Basil Bourque
May 26 '18 at 6:25
I suggest adding a link to the JavaEE library.
– Basil Bourque
May 26 '18 at 6:25
add a comment |
quick-json parser is very straightforward, flexible, very fast and customizable. Try it
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
It can be used like this:
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
3
Is there a javadoc available?
– jboi
Sep 10 '13 at 11:38
20
This package cannot handle empty values when parsing. For example: ... "description":"" ... throws an Exception
– Ivan
Oct 25 '13 at 15:45
6
I've fixed this issue (and many others) in code.google.com/p/quick-json/issues/detail?id=11 I hope the author will give take the time to fix it in the official release.
– noamik
Aug 8 '14 at 12:28
8
Of listed features, nothing is unique compared to other options -- and claim of high-performance is not supported by anything; unlike for more mature libraries (Gson, Jackson, Genson, Boon) which are included in benchmarks like github.com/eishay/jvm-serializers, github.com/novoj/JavaJsonPerformanceTest or developer.com/lang/jscript/… -- I have not seen this library included in tests, or mentions of it being widely used.
– StaxMan
Oct 24 '14 at 5:12
18
This project appears to be dead and appears to be no longer hosted in the central Maven repository.
– 8bitjunkie
Nov 8 '15 at 22:16
|
show 4 more comments
quick-json parser is very straightforward, flexible, very fast and customizable. Try it
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
It can be used like this:
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
3
Is there a javadoc available?
– jboi
Sep 10 '13 at 11:38
20
This package cannot handle empty values when parsing. For example: ... "description":"" ... throws an Exception
– Ivan
Oct 25 '13 at 15:45
6
I've fixed this issue (and many others) in code.google.com/p/quick-json/issues/detail?id=11 I hope the author will give take the time to fix it in the official release.
– noamik
Aug 8 '14 at 12:28
8
Of listed features, nothing is unique compared to other options -- and claim of high-performance is not supported by anything; unlike for more mature libraries (Gson, Jackson, Genson, Boon) which are included in benchmarks like github.com/eishay/jvm-serializers, github.com/novoj/JavaJsonPerformanceTest or developer.com/lang/jscript/… -- I have not seen this library included in tests, or mentions of it being widely used.
– StaxMan
Oct 24 '14 at 5:12
18
This project appears to be dead and appears to be no longer hosted in the central Maven repository.
– 8bitjunkie
Nov 8 '15 at 22:16
|
show 4 more comments
quick-json parser is very straightforward, flexible, very fast and customizable. Try it
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
It can be used like this:
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
quick-json parser is very straightforward, flexible, very fast and customizable. Try it
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
It can be used like this:
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
edited Feb 27 '17 at 13:18
mukesh krishnan
74215
74215
answered Feb 24 '13 at 6:24
rputtarputta
793153
793153
3
Is there a javadoc available?
– jboi
Sep 10 '13 at 11:38
20
This package cannot handle empty values when parsing. For example: ... "description":"" ... throws an Exception
– Ivan
Oct 25 '13 at 15:45
6
I've fixed this issue (and many others) in code.google.com/p/quick-json/issues/detail?id=11 I hope the author will give take the time to fix it in the official release.
– noamik
Aug 8 '14 at 12:28
8
Of listed features, nothing is unique compared to other options -- and claim of high-performance is not supported by anything; unlike for more mature libraries (Gson, Jackson, Genson, Boon) which are included in benchmarks like github.com/eishay/jvm-serializers, github.com/novoj/JavaJsonPerformanceTest or developer.com/lang/jscript/… -- I have not seen this library included in tests, or mentions of it being widely used.
– StaxMan
Oct 24 '14 at 5:12
18
This project appears to be dead and appears to be no longer hosted in the central Maven repository.
– 8bitjunkie
Nov 8 '15 at 22:16
|
show 4 more comments
3
Is there a javadoc available?
– jboi
Sep 10 '13 at 11:38
20
This package cannot handle empty values when parsing. For example: ... "description":"" ... throws an Exception
– Ivan
Oct 25 '13 at 15:45
6
I've fixed this issue (and many others) in code.google.com/p/quick-json/issues/detail?id=11 I hope the author will give take the time to fix it in the official release.
– noamik
Aug 8 '14 at 12:28
8
Of listed features, nothing is unique compared to other options -- and claim of high-performance is not supported by anything; unlike for more mature libraries (Gson, Jackson, Genson, Boon) which are included in benchmarks like github.com/eishay/jvm-serializers, github.com/novoj/JavaJsonPerformanceTest or developer.com/lang/jscript/… -- I have not seen this library included in tests, or mentions of it being widely used.
– StaxMan
Oct 24 '14 at 5:12
18
This project appears to be dead and appears to be no longer hosted in the central Maven repository.
– 8bitjunkie
Nov 8 '15 at 22:16
3
3
Is there a javadoc available?
– jboi
Sep 10 '13 at 11:38
Is there a javadoc available?
– jboi
Sep 10 '13 at 11:38
20
20
This package cannot handle empty values when parsing. For example: ... "description":"" ... throws an Exception
– Ivan
Oct 25 '13 at 15:45
This package cannot handle empty values when parsing. For example: ... "description":"" ... throws an Exception
– Ivan
Oct 25 '13 at 15:45
6
6
I've fixed this issue (and many others) in code.google.com/p/quick-json/issues/detail?id=11 I hope the author will give take the time to fix it in the official release.
– noamik
Aug 8 '14 at 12:28
I've fixed this issue (and many others) in code.google.com/p/quick-json/issues/detail?id=11 I hope the author will give take the time to fix it in the official release.
– noamik
Aug 8 '14 at 12:28
8
8
Of listed features, nothing is unique compared to other options -- and claim of high-performance is not supported by anything; unlike for more mature libraries (Gson, Jackson, Genson, Boon) which are included in benchmarks like github.com/eishay/jvm-serializers, github.com/novoj/JavaJsonPerformanceTest or developer.com/lang/jscript/… -- I have not seen this library included in tests, or mentions of it being widely used.
– StaxMan
Oct 24 '14 at 5:12
Of listed features, nothing is unique compared to other options -- and claim of high-performance is not supported by anything; unlike for more mature libraries (Gson, Jackson, Genson, Boon) which are included in benchmarks like github.com/eishay/jvm-serializers, github.com/novoj/JavaJsonPerformanceTest or developer.com/lang/jscript/… -- I have not seen this library included in tests, or mentions of it being widely used.
– StaxMan
Oct 24 '14 at 5:12
18
18
This project appears to be dead and appears to be no longer hosted in the central Maven repository.
– 8bitjunkie
Nov 8 '15 at 22:16
This project appears to be dead and appears to be no longer hosted in the central Maven repository.
– 8bitjunkie
Nov 8 '15 at 22:16
|
show 4 more comments
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 JsonPATH which is like XPath for JSON and allows traversing of JSON objects.
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
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.
add a comment |
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 JsonPATH which is like XPath for JSON and allows traversing of JSON objects.
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
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.
add a comment |
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 JsonPATH which is like XPath for JSON and allows traversing of JSON objects.
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
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.
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 JsonPATH which is like XPath for JSON and allows traversing of JSON objects.
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
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.
answered Dec 16 '15 at 13:51
dadedade
1,45231932
1,45231932
add a comment |
add a comment |
A - Explanation
You can use Jackson libraries, for binding JSON String into POJO (Plain Old Java Object) instances. POJO is simply a class with only private fields and public getter/setter methods. Jackson is going to traverse the methods (using reflection), and maps the JSON object into the POJO instance as the field names of the class fits to the field names of the JSON object.
In your JSON object, which is actually a composite object, the main object consists o two sub-objects. So, our POJO classes should have the same hierarchy. I'll call the whole JSON Object as Page object. Page object consist of a PageInfo object, and a Post object array.
So we have to create three different POJO classes;
Page Class, a composite of PageInfo Class and array of Post Instances
PageInfo Class
Posts Class
The only package I've used is Jackson ObjectMapper, what we do is binding data;
com.fasterxml.jackson.databind.ObjectMapper
The required dependencies, the jar files is listed below;
- jackson-core-2.5.1.jar
- jackson-databind-2.5.1.jar
- jackson-annotations-2.5.0.jar
Here is the required code;
B - Main POJO Class : Page
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 - Child POJO Class : 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 - Child POJO Class : Post
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;
}
}
E - Sample JSON File : sampleJSONFile.json
I've just copied your JSON sample into this file and put it under the project folder.
{
"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 - Demo Code
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 - Demo Output
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
add a comment |
A - Explanation
You can use Jackson libraries, for binding JSON String into POJO (Plain Old Java Object) instances. POJO is simply a class with only private fields and public getter/setter methods. Jackson is going to traverse the methods (using reflection), and maps the JSON object into the POJO instance as the field names of the class fits to the field names of the JSON object.
In your JSON object, which is actually a composite object, the main object consists o two sub-objects. So, our POJO classes should have the same hierarchy. I'll call the whole JSON Object as Page object. Page object consist of a PageInfo object, and a Post object array.
So we have to create three different POJO classes;
Page Class, a composite of PageInfo Class and array of Post Instances
PageInfo Class
Posts Class
The only package I've used is Jackson ObjectMapper, what we do is binding data;
com.fasterxml.jackson.databind.ObjectMapper
The required dependencies, the jar files is listed below;
- jackson-core-2.5.1.jar
- jackson-databind-2.5.1.jar
- jackson-annotations-2.5.0.jar
Here is the required code;
B - Main POJO Class : Page
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 - Child POJO Class : 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 - Child POJO Class : Post
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;
}
}
E - Sample JSON File : sampleJSONFile.json
I've just copied your JSON sample into this file and put it under the project folder.
{
"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 - Demo Code
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 - Demo Output
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
add a comment |
A - Explanation
You can use Jackson libraries, for binding JSON String into POJO (Plain Old Java Object) instances. POJO is simply a class with only private fields and public getter/setter methods. Jackson is going to traverse the methods (using reflection), and maps the JSON object into the POJO instance as the field names of the class fits to the field names of the JSON object.
In your JSON object, which is actually a composite object, the main object consists o two sub-objects. So, our POJO classes should have the same hierarchy. I'll call the whole JSON Object as Page object. Page object consist of a PageInfo object, and a Post object array.
So we have to create three different POJO classes;
Page Class, a composite of PageInfo Class and array of Post Instances
PageInfo Class
Posts Class
The only package I've used is Jackson ObjectMapper, what we do is binding data;
com.fasterxml.jackson.databind.ObjectMapper
The required dependencies, the jar files is listed below;
- jackson-core-2.5.1.jar
- jackson-databind-2.5.1.jar
- jackson-annotations-2.5.0.jar
Here is the required code;
B - Main POJO Class : Page
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 - Child POJO Class : 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 - Child POJO Class : Post
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;
}
}
E - Sample JSON File : sampleJSONFile.json
I've just copied your JSON sample into this file and put it under the project folder.
{
"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 - Demo Code
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 - Demo Output
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
A - Explanation
You can use Jackson libraries, for binding JSON String into POJO (Plain Old Java Object) instances. POJO is simply a class with only private fields and public getter/setter methods. Jackson is going to traverse the methods (using reflection), and maps the JSON object into the POJO instance as the field names of the class fits to the field names of the JSON object.
In your JSON object, which is actually a composite object, the main object consists o two sub-objects. So, our POJO classes should have the same hierarchy. I'll call the whole JSON Object as Page object. Page object consist of a PageInfo object, and a Post object array.
So we have to create three different POJO classes;
Page Class, a composite of PageInfo Class and array of Post Instances
PageInfo Class
Posts Class
The only package I've used is Jackson ObjectMapper, what we do is binding data;
com.fasterxml.jackson.databind.ObjectMapper
The required dependencies, the jar files is listed below;
- jackson-core-2.5.1.jar
- jackson-databind-2.5.1.jar
- jackson-annotations-2.5.0.jar
Here is the required code;
B - Main POJO Class : Page
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 - Child POJO Class : 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 - Child POJO Class : Post
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;
}
}
E - Sample JSON File : sampleJSONFile.json
I've just copied your JSON sample into this file and put it under the project folder.
{
"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 - Demo Code
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 - Demo Output
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
edited Jul 12 '16 at 19:42
answered Jul 12 '16 at 19:06
Levent DiviliogluLevent Divilioglu
6,43433383
6,43433383
add a comment |
add a comment |
You could use Google Gson.
Using this library you only need to create a model with the same JSON structure. Then the model is automatically filled in. You have to call your variables as your JSON keys, or use @SerializedName if you want to use different names.
For your example:
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"
}
]
}
Model:
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;
}
Now you can parse using Gson library:
MyModel model = gson.fromJson(jsonString, MyModel.class);
You can generate model from JSON automatically using online tools like this.
add a comment |
You could use Google Gson.
Using this library you only need to create a model with the same JSON structure. Then the model is automatically filled in. You have to call your variables as your JSON keys, or use @SerializedName if you want to use different names.
For your example:
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"
}
]
}
Model:
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;
}
Now you can parse using Gson library:
MyModel model = gson.fromJson(jsonString, MyModel.class);
You can generate model from JSON automatically using online tools like this.
add a comment |
You could use Google Gson.
Using this library you only need to create a model with the same JSON structure. Then the model is automatically filled in. You have to call your variables as your JSON keys, or use @SerializedName if you want to use different names.
For your example:
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"
}
]
}
Model:
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;
}
Now you can parse using Gson library:
MyModel model = gson.fromJson(jsonString, MyModel.class);
You can generate model from JSON automatically using online tools like this.
You could use Google Gson.
Using this library you only need to create a model with the same JSON structure. Then the model is automatically filled in. You have to call your variables as your JSON keys, or use @SerializedName if you want to use different names.
For your example:
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"
}
]
}
Model:
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;
}
Now you can parse using Gson library:
MyModel model = gson.fromJson(jsonString, MyModel.class);
You can generate model from JSON automatically using online tools like this.
edited Oct 8 '18 at 23:29
answered Jun 1 '16 at 15:20
lubilislubilis
2,54532043
2,54532043
add a comment |
add a comment |
Use minimal-json which is very fast and easy to use.
You can parse from String obj and Stream.
Sample data:
{
"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();
Creating JSON:
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>
How does the pojo will look?
– Jesse
Mar 29 '17 at 15:24
For Pojo use gson. This library doesn't support.
– Sakib Sami
Mar 29 '17 at 20:01
add a comment |
Use minimal-json which is very fast and easy to use.
You can parse from String obj and Stream.
Sample data:
{
"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();
Creating JSON:
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>
How does the pojo will look?
– Jesse
Mar 29 '17 at 15:24
For Pojo use gson. This library doesn't support.
– Sakib Sami
Mar 29 '17 at 20:01
add a comment |
Use minimal-json which is very fast and easy to use.
You can parse from String obj and Stream.
Sample data:
{
"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();
Creating JSON:
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>
Use minimal-json which is very fast and easy to use.
You can parse from String obj and Stream.
Sample data:
{
"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();
Creating JSON:
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>
edited Feb 4 '18 at 18:48
Peter Mortensen
13.7k1986112
13.7k1986112
answered Aug 15 '16 at 19:57
Sakib SamiSakib Sami
826913
826913
How does the pojo will look?
– Jesse
Mar 29 '17 at 15:24
For Pojo use gson. This library doesn't support.
– Sakib Sami
Mar 29 '17 at 20:01
add a comment |
How does the pojo will look?
– Jesse
Mar 29 '17 at 15:24
For Pojo use gson. This library doesn't support.
– Sakib Sami
Mar 29 '17 at 20:01
How does the pojo will look?
– Jesse
Mar 29 '17 at 15:24
How does the pojo will look?
– Jesse
Mar 29 '17 at 15:24
For Pojo use gson. This library doesn't support.
– Sakib Sami
Mar 29 '17 at 20:01
For Pojo use gson. This library doesn't support.
– Sakib Sami
Mar 29 '17 at 20:01
add a comment |
I believe the best practice should be to go through the official Java JSON API which are still work in progress.
7
Since I replied, I started using Jackson and I think it's one of the best libraries out there for JSON de-serialization.
– Giovanni Botta
Sep 11 '14 at 14:26
2
Why do they re-use JSONP to mean something different than JSON with Padding?...
– Chris Wesseling
May 14 '15 at 5:53
@ChrisWesseling What do you mean?
– Giovanni Botta
May 14 '15 at 18:43
"Java API for JSON Processing (JSON-P)" is the title of the document you link to. And it confused me, because I knew JSONP to mean something else.
– Chris Wesseling
May 14 '15 at 18:48
1
@ChrisWesseling oh that is confusing. That's what they chose for the specification. However as I said, I would go straight to Jackson.
– Giovanni Botta
May 14 '15 at 18:50
|
show 1 more comment
I believe the best practice should be to go through the official Java JSON API which are still work in progress.
7
Since I replied, I started using Jackson and I think it's one of the best libraries out there for JSON de-serialization.
– Giovanni Botta
Sep 11 '14 at 14:26
2
Why do they re-use JSONP to mean something different than JSON with Padding?...
– Chris Wesseling
May 14 '15 at 5:53
@ChrisWesseling What do you mean?
– Giovanni Botta
May 14 '15 at 18:43
"Java API for JSON Processing (JSON-P)" is the title of the document you link to. And it confused me, because I knew JSONP to mean something else.
– Chris Wesseling
May 14 '15 at 18:48
1
@ChrisWesseling oh that is confusing. That's what they chose for the specification. However as I said, I would go straight to Jackson.
– Giovanni Botta
May 14 '15 at 18:50
|
show 1 more comment
I believe the best practice should be to go through the official Java JSON API which are still work in progress.
I believe the best practice should be to go through the official Java JSON API which are still work in progress.
edited Aug 14 '15 at 0:04
Iharob Al Asimi
48.5k54379
48.5k54379
answered Apr 8 '13 at 17:37
Giovanni BottaGiovanni Botta
6,76353584
6,76353584
7
Since I replied, I started using Jackson and I think it's one of the best libraries out there for JSON de-serialization.
– Giovanni Botta
Sep 11 '14 at 14:26
2
Why do they re-use JSONP to mean something different than JSON with Padding?...
– Chris Wesseling
May 14 '15 at 5:53
@ChrisWesseling What do you mean?
– Giovanni Botta
May 14 '15 at 18:43
"Java API for JSON Processing (JSON-P)" is the title of the document you link to. And it confused me, because I knew JSONP to mean something else.
– Chris Wesseling
May 14 '15 at 18:48
1
@ChrisWesseling oh that is confusing. That's what they chose for the specification. However as I said, I would go straight to Jackson.
– Giovanni Botta
May 14 '15 at 18:50
|
show 1 more comment
7
Since I replied, I started using Jackson and I think it's one of the best libraries out there for JSON de-serialization.
– Giovanni Botta
Sep 11 '14 at 14:26
2
Why do they re-use JSONP to mean something different than JSON with Padding?...
– Chris Wesseling
May 14 '15 at 5:53
@ChrisWesseling What do you mean?
– Giovanni Botta
May 14 '15 at 18:43
"Java API for JSON Processing (JSON-P)" is the title of the document you link to. And it confused me, because I knew JSONP to mean something else.
– Chris Wesseling
May 14 '15 at 18:48
1
@ChrisWesseling oh that is confusing. That's what they chose for the specification. However as I said, I would go straight to Jackson.
– Giovanni Botta
May 14 '15 at 18:50
7
7
Since I replied, I started using Jackson and I think it's one of the best libraries out there for JSON de-serialization.
– Giovanni Botta
Sep 11 '14 at 14:26
Since I replied, I started using Jackson and I think it's one of the best libraries out there for JSON de-serialization.
– Giovanni Botta
Sep 11 '14 at 14:26
2
2
Why do they re-use JSONP to mean something different than JSON with Padding?...
– Chris Wesseling
May 14 '15 at 5:53
Why do they re-use JSONP to mean something different than JSON with Padding?...
– Chris Wesseling
May 14 '15 at 5:53
@ChrisWesseling What do you mean?
– Giovanni Botta
May 14 '15 at 18:43
@ChrisWesseling What do you mean?
– Giovanni Botta
May 14 '15 at 18:43
"Java API for JSON Processing (JSON-P)" is the title of the document you link to. And it confused me, because I knew JSONP to mean something else.
– Chris Wesseling
May 14 '15 at 18:48
"Java API for JSON Processing (JSON-P)" is the title of the document you link to. And it confused me, because I knew JSONP to mean something else.
– Chris Wesseling
May 14 '15 at 18:48
1
1
@ChrisWesseling oh that is confusing. That's what they chose for the specification. However as I said, I would go straight to Jackson.
– Giovanni Botta
May 14 '15 at 18:50
@ChrisWesseling oh that is confusing. That's what they chose for the specification. However as I said, I would go straight to Jackson.
– Giovanni Botta
May 14 '15 at 18:50
|
show 1 more comment
The below example shows how to read the text in the question, represented as the "jsonText" variable. This solution uses the Java EE7 javax.json API (which is mentioned in some of the other answers). The reason I've added it as a separate answer is that the following code shows how to actually access some of the values shown in the question. An implementation of the javax.json API would be required to make this code run. The full package for each of the classes required was included as I didn't want to declare "import" statements.
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");
Now, before anyone goes and downvotes this answer because it doesn't use GSON, org.json, Jackson, or any of the other 3rd party frameworks available, it's an example of "required code" per the question to parse the provided text. I am well aware that adherence to the current standard JSR 353 was not being considered for JDK 9 and as such the JSR 353 spec should be treated the same as any other 3rd party JSON handling implementation.
add a comment |
The below example shows how to read the text in the question, represented as the "jsonText" variable. This solution uses the Java EE7 javax.json API (which is mentioned in some of the other answers). The reason I've added it as a separate answer is that the following code shows how to actually access some of the values shown in the question. An implementation of the javax.json API would be required to make this code run. The full package for each of the classes required was included as I didn't want to declare "import" statements.
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");
Now, before anyone goes and downvotes this answer because it doesn't use GSON, org.json, Jackson, or any of the other 3rd party frameworks available, it's an example of "required code" per the question to parse the provided text. I am well aware that adherence to the current standard JSR 353 was not being considered for JDK 9 and as such the JSR 353 spec should be treated the same as any other 3rd party JSON handling implementation.
add a comment |
The below example shows how to read the text in the question, represented as the "jsonText" variable. This solution uses the Java EE7 javax.json API (which is mentioned in some of the other answers). The reason I've added it as a separate answer is that the following code shows how to actually access some of the values shown in the question. An implementation of the javax.json API would be required to make this code run. The full package for each of the classes required was included as I didn't want to declare "import" statements.
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");
Now, before anyone goes and downvotes this answer because it doesn't use GSON, org.json, Jackson, or any of the other 3rd party frameworks available, it's an example of "required code" per the question to parse the provided text. I am well aware that adherence to the current standard JSR 353 was not being considered for JDK 9 and as such the JSR 353 spec should be treated the same as any other 3rd party JSON handling implementation.
The below example shows how to read the text in the question, represented as the "jsonText" variable. This solution uses the Java EE7 javax.json API (which is mentioned in some of the other answers). The reason I've added it as a separate answer is that the following code shows how to actually access some of the values shown in the question. An implementation of the javax.json API would be required to make this code run. The full package for each of the classes required was included as I didn't want to declare "import" statements.
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");
Now, before anyone goes and downvotes this answer because it doesn't use GSON, org.json, Jackson, or any of the other 3rd party frameworks available, it's an example of "required code" per the question to parse the provided text. I am well aware that adherence to the current standard JSR 353 was not being considered for JDK 9 and as such the JSR 353 spec should be treated the same as any other 3rd party JSON handling implementation.
answered May 2 '16 at 21:58
justin.hugheyjustin.hughey
9861015
9861015
add a comment |
add a comment |
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.
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.
10
TheJSONArraytype is not part of the J2SE JDK API and you don't say which API or third-party library provides this type.
– Bobulous
Apr 24 '15 at 22:22
2
Not that I would recommend using it, but I think this refers to the "org.json" package from json.org/java. It used to be used before good Java libraries became available, but this was years ago (2008 or before)
– StaxMan
Jun 1 '15 at 23:11
Or does brainmurphy1 mean JSONArray in Android?
– Alexander Farber
Feb 21 '18 at 13:44
add a comment |
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.
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.
10
TheJSONArraytype is not part of the J2SE JDK API and you don't say which API or third-party library provides this type.
– Bobulous
Apr 24 '15 at 22:22
2
Not that I would recommend using it, but I think this refers to the "org.json" package from json.org/java. It used to be used before good Java libraries became available, but this was years ago (2008 or before)
– StaxMan
Jun 1 '15 at 23:11
Or does brainmurphy1 mean JSONArray in Android?
– Alexander Farber
Feb 21 '18 at 13:44
add a comment |
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.
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.
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.
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.
edited Jan 15 '16 at 19:45
jpaugh
3,86632468
3,86632468
answered May 15 '14 at 1:56
brainmurphy1brainmurphy1
84011822
84011822
10
TheJSONArraytype is not part of the J2SE JDK API and you don't say which API or third-party library provides this type.
– Bobulous
Apr 24 '15 at 22:22
2
Not that I would recommend using it, but I think this refers to the "org.json" package from json.org/java. It used to be used before good Java libraries became available, but this was years ago (2008 or before)
– StaxMan
Jun 1 '15 at 23:11
Or does brainmurphy1 mean JSONArray in Android?
– Alexander Farber
Feb 21 '18 at 13:44
add a comment |
10
TheJSONArraytype is not part of the J2SE JDK API and you don't say which API or third-party library provides this type.
– Bobulous
Apr 24 '15 at 22:22
2
Not that I would recommend using it, but I think this refers to the "org.json" package from json.org/java. It used to be used before good Java libraries became available, but this was years ago (2008 or before)
– StaxMan
Jun 1 '15 at 23:11
Or does brainmurphy1 mean JSONArray in Android?
– Alexander Farber
Feb 21 '18 at 13:44
10
10
The
JSONArray type is not part of the J2SE JDK API and you don't say which API or third-party library provides this type.– Bobulous
Apr 24 '15 at 22:22
The
JSONArray type is not part of the J2SE JDK API and you don't say which API or third-party library provides this type.– Bobulous
Apr 24 '15 at 22:22
2
2
Not that I would recommend using it, but I think this refers to the "org.json" package from json.org/java. It used to be used before good Java libraries became available, but this was years ago (2008 or before)
– StaxMan
Jun 1 '15 at 23:11
Not that I would recommend using it, but I think this refers to the "org.json" package from json.org/java. It used to be used before good Java libraries became available, but this was years ago (2008 or before)
– StaxMan
Jun 1 '15 at 23:11
Or does brainmurphy1 mean JSONArray in Android?
– Alexander Farber
Feb 21 '18 at 13:44
Or does brainmurphy1 mean JSONArray in Android?
– Alexander Farber
Feb 21 '18 at 13:44
add a comment |
Since nobody mentioned it yet, here is a beginning of a solution using Nashorn (JavaScript runtime part of Java 8, but deprecated in Java 11).
Solution
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));
}
Performance comparison
I wrote JSON content containing three arrays of respectively 20, 20 and 100 elements. I only want to get the 100 elements from the third array. I use the following JavaScript function to parse and get my entries.
var fun = function(raw) {JSON.parse(raw).entries};
Running the call a million times using Nashorn takes 7.5~7.8 seconds
(JSObject) invocable.invokeFunction("fun", json);
org.json takes 20~21 seconds
new JSONObject(JSON).getJSONArray("entries");
Jackson takes 6.5~7 seconds
mapper.readValue(JSON, Entries.class).getEntries();
In this case Jackson performs better than Nashorn, which performs much better than org.json.
Nashorn API is harder to use than org.json's or Jackson's. Depending on your requirements Jackson and Nashorn both can be viable solutions.
1
What is the unit """? Not inches? Is it seconds? Minutes?
– Peter Mortensen
Feb 4 '18 at 18:55
1
@PeterMortensen it means seconds. Since it seems unclear I'll change it. Thanks for the review.
– otonglet
Feb 5 '18 at 9:18
1
Unfortunately, Nashorn is deprecated in Java 11. JEP 335.
– Per Mildner
Oct 25 '18 at 13:14
add a comment |
Since nobody mentioned it yet, here is a beginning of a solution using Nashorn (JavaScript runtime part of Java 8, but deprecated in Java 11).
Solution
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));
}
Performance comparison
I wrote JSON content containing three arrays of respectively 20, 20 and 100 elements. I only want to get the 100 elements from the third array. I use the following JavaScript function to parse and get my entries.
var fun = function(raw) {JSON.parse(raw).entries};
Running the call a million times using Nashorn takes 7.5~7.8 seconds
(JSObject) invocable.invokeFunction("fun", json);
org.json takes 20~21 seconds
new JSONObject(JSON).getJSONArray("entries");
Jackson takes 6.5~7 seconds
mapper.readValue(JSON, Entries.class).getEntries();
In this case Jackson performs better than Nashorn, which performs much better than org.json.
Nashorn API is harder to use than org.json's or Jackson's. Depending on your requirements Jackson and Nashorn both can be viable solutions.
1
What is the unit """? Not inches? Is it seconds? Minutes?
– Peter Mortensen
Feb 4 '18 at 18:55
1
@PeterMortensen it means seconds. Since it seems unclear I'll change it. Thanks for the review.
– otonglet
Feb 5 '18 at 9:18
1
Unfortunately, Nashorn is deprecated in Java 11. JEP 335.
– Per Mildner
Oct 25 '18 at 13:14
add a comment |
Since nobody mentioned it yet, here is a beginning of a solution using Nashorn (JavaScript runtime part of Java 8, but deprecated in Java 11).
Solution
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));
}
Performance comparison
I wrote JSON content containing three arrays of respectively 20, 20 and 100 elements. I only want to get the 100 elements from the third array. I use the following JavaScript function to parse and get my entries.
var fun = function(raw) {JSON.parse(raw).entries};
Running the call a million times using Nashorn takes 7.5~7.8 seconds
(JSObject) invocable.invokeFunction("fun", json);
org.json takes 20~21 seconds
new JSONObject(JSON).getJSONArray("entries");
Jackson takes 6.5~7 seconds
mapper.readValue(JSON, Entries.class).getEntries();
In this case Jackson performs better than Nashorn, which performs much better than org.json.
Nashorn API is harder to use than org.json's or Jackson's. Depending on your requirements Jackson and Nashorn both can be viable solutions.
Since nobody mentioned it yet, here is a beginning of a solution using Nashorn (JavaScript runtime part of Java 8, but deprecated in Java 11).
Solution
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));
}
Performance comparison
I wrote JSON content containing three arrays of respectively 20, 20 and 100 elements. I only want to get the 100 elements from the third array. I use the following JavaScript function to parse and get my entries.
var fun = function(raw) {JSON.parse(raw).entries};
Running the call a million times using Nashorn takes 7.5~7.8 seconds
(JSObject) invocable.invokeFunction("fun", json);
org.json takes 20~21 seconds
new JSONObject(JSON).getJSONArray("entries");
Jackson takes 6.5~7 seconds
mapper.readValue(JSON, Entries.class).getEntries();
In this case Jackson performs better than Nashorn, which performs much better than org.json.
Nashorn API is harder to use than org.json's or Jackson's. Depending on your requirements Jackson and Nashorn both can be viable solutions.
edited Oct 26 '18 at 10:15
answered Feb 8 '17 at 7:09
otongletotonglet
2,2851430
2,2851430
1
What is the unit """? Not inches? Is it seconds? Minutes?
– Peter Mortensen
Feb 4 '18 at 18:55
1
@PeterMortensen it means seconds. Since it seems unclear I'll change it. Thanks for the review.
– otonglet
Feb 5 '18 at 9:18
1
Unfortunately, Nashorn is deprecated in Java 11. JEP 335.
– Per Mildner
Oct 25 '18 at 13:14
add a comment |
1
What is the unit """? Not inches? Is it seconds? Minutes?
– Peter Mortensen
Feb 4 '18 at 18:55
1
@PeterMortensen it means seconds. Since it seems unclear I'll change it. Thanks for the review.
– otonglet
Feb 5 '18 at 9:18
1
Unfortunately, Nashorn is deprecated in Java 11. JEP 335.
– Per Mildner
Oct 25 '18 at 13:14
1
1
What is the unit "
""? Not inches? Is it seconds? Minutes?– Peter Mortensen
Feb 4 '18 at 18:55
What is the unit "
""? Not inches? Is it seconds? Minutes?– Peter Mortensen
Feb 4 '18 at 18:55
1
1
@PeterMortensen it means seconds. Since it seems unclear I'll change it. Thanks for the review.
– otonglet
Feb 5 '18 at 9:18
@PeterMortensen it means seconds. Since it seems unclear I'll change it. Thanks for the review.
– otonglet
Feb 5 '18 at 9:18
1
1
Unfortunately, Nashorn is deprecated in Java 11. JEP 335.
– Per Mildner
Oct 25 '18 at 13:14
Unfortunately, Nashorn is deprecated in Java 11. JEP 335.
– Per Mildner
Oct 25 '18 at 13:14
add a comment |
There are many JSON libraries available in Java.
The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.
There are typically three things one should look at for choosing any library:
- Performance
- Ease of use (code is simple to write and legible) - that goes with features.
- For mobile apps: dependency/jar size
Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.
For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs.
For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...
Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.
For your particular example, the following code decodes your json with jackson:
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.
}
}
Let me know if you have any questions.
add a comment |
There are many JSON libraries available in Java.
The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.
There are typically three things one should look at for choosing any library:
- Performance
- Ease of use (code is simple to write and legible) - that goes with features.
- For mobile apps: dependency/jar size
Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.
For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs.
For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...
Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.
For your particular example, the following code decodes your json with jackson:
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.
}
}
Let me know if you have any questions.
add a comment |
There are many JSON libraries available in Java.
The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.
There are typically three things one should look at for choosing any library:
- Performance
- Ease of use (code is simple to write and legible) - that goes with features.
- For mobile apps: dependency/jar size
Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.
For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs.
For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...
Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.
For your particular example, the following code decodes your json with jackson:
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.
}
}
Let me know if you have any questions.
There are many JSON libraries available in Java.
The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.
There are typically three things one should look at for choosing any library:
- Performance
- Ease of use (code is simple to write and legible) - that goes with features.
- For mobile apps: dependency/jar size
Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.
For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs.
For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...
Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.
For your particular example, the following code decodes your json with jackson:
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.
}
}
Let me know if you have any questions.
edited Jun 29 '16 at 5:09
answered Jun 27 '16 at 20:32
fabienfabien
934921
934921
add a comment |
add a comment |
If you have some Java class(say Message) representing the JSON string(jsonString), you can use Jackson JSON library with:
Message message= new ObjectMapper().readValue(jsonString, Message.class);
and from message object you can fetch any of its attribute.
add a comment |
If you have some Java class(say Message) representing the JSON string(jsonString), you can use Jackson JSON library with:
Message message= new ObjectMapper().readValue(jsonString, Message.class);
and from message object you can fetch any of its attribute.
add a comment |
If you have some Java class(say Message) representing the JSON string(jsonString), you can use Jackson JSON library with:
Message message= new ObjectMapper().readValue(jsonString, Message.class);
and from message object you can fetch any of its attribute.
If you have some Java class(say Message) representing the JSON string(jsonString), you can use Jackson JSON library with:
Message message= new ObjectMapper().readValue(jsonString, Message.class);
and from message object you can fetch any of its attribute.
edited Oct 6 '15 at 18:08
StaxMan
82.5k24163201
82.5k24163201
answered Aug 29 '15 at 12:39
Shailendra SinghShailendra Singh
35639
35639
add a comment |
add a comment |
In addition to other answers, I recomend this online opensource service jsonschema2pojo.org for quick generating Java classes from json or json schema for GSON, Jackson 1.x or Jackson 2.x. For example, if you have:
{
"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
}
]
}
The jsonschema2pojo.org for GSON generated:
@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;
}
add a comment |
In addition to other answers, I recomend this online opensource service jsonschema2pojo.org for quick generating Java classes from json or json schema for GSON, Jackson 1.x or Jackson 2.x. For example, if you have:
{
"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
}
]
}
The jsonschema2pojo.org for GSON generated:
@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;
}
add a comment |
In addition to other answers, I recomend this online opensource service jsonschema2pojo.org for quick generating Java classes from json or json schema for GSON, Jackson 1.x or Jackson 2.x. For example, if you have:
{
"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
}
]
}
The jsonschema2pojo.org for GSON generated:
@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;
}
In addition to other answers, I recomend this online opensource service jsonschema2pojo.org for quick generating Java classes from json or json schema for GSON, Jackson 1.x or Jackson 2.x. For example, if you have:
{
"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
}
]
}
The jsonschema2pojo.org for GSON generated:
@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;
}
answered Dec 16 '15 at 21:23
Viacheslav VedeninViacheslav Vedenin
34.4k133253
34.4k133253
add a comment |
add a comment |
There are many open source libraries present to parse JSON content to an object or just to read JSON values. Your requirement is just to read values and parsing it to custom object. So org.json library is enough in your case.
Use org.json library to parse it and create JsonObject:
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values:
String id = jsonObj.getString("pageInfo");
You can see a complete example here:
How to parse JSON in Java
It seems like all your answers contain a link to that site. If it's spam, please stop. If it's not, sorry for the confusion, but I don't think that it's necessary to post a link in all your answers.
– Donald Duck
Mar 3 '17 at 12:43
1
Its tough to give an answer, where you can explain all scenarios. Like in this case, how to read json array or multiple json objects. Even If I do so, answer would be very long and person may get confuse. So I give a link where proper explanation is given, with proper example. He can chose to visit or can use only my explanation only.
– lalitbhagtani
Mar 3 '17 at 12:51
1
It appears to me that the link you have provided only demonstrates how to read JSON. Where can I find info on how to JSON as well?
– Lampros Tzanetos
Oct 27 '17 at 12:53
Sorry, but I didn't understand your question :- "on how to JSON as well"
– lalitbhagtani
Oct 31 '17 at 7:56
add a comment |
There are many open source libraries present to parse JSON content to an object or just to read JSON values. Your requirement is just to read values and parsing it to custom object. So org.json library is enough in your case.
Use org.json library to parse it and create JsonObject:
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values:
String id = jsonObj.getString("pageInfo");
You can see a complete example here:
How to parse JSON in Java
It seems like all your answers contain a link to that site. If it's spam, please stop. If it's not, sorry for the confusion, but I don't think that it's necessary to post a link in all your answers.
– Donald Duck
Mar 3 '17 at 12:43
1
Its tough to give an answer, where you can explain all scenarios. Like in this case, how to read json array or multiple json objects. Even If I do so, answer would be very long and person may get confuse. So I give a link where proper explanation is given, with proper example. He can chose to visit or can use only my explanation only.
– lalitbhagtani
Mar 3 '17 at 12:51
1
It appears to me that the link you have provided only demonstrates how to read JSON. Where can I find info on how to JSON as well?
– Lampros Tzanetos
Oct 27 '17 at 12:53
Sorry, but I didn't understand your question :- "on how to JSON as well"
– lalitbhagtani
Oct 31 '17 at 7:56
add a comment |
There are many open source libraries present to parse JSON content to an object or just to read JSON values. Your requirement is just to read values and parsing it to custom object. So org.json library is enough in your case.
Use org.json library to parse it and create JsonObject:
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values:
String id = jsonObj.getString("pageInfo");
You can see a complete example here:
How to parse JSON in Java
There are many open source libraries present to parse JSON content to an object or just to read JSON values. Your requirement is just to read values and parsing it to custom object. So org.json library is enough in your case.
Use org.json library to parse it and create JsonObject:
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values:
String id = jsonObj.getString("pageInfo");
You can see a complete example here:
How to parse JSON in Java
edited Feb 4 '18 at 19:00
Peter Mortensen
13.7k1986112
13.7k1986112
answered Mar 3 '17 at 12:17
lalitbhagtanilalitbhagtani
33336
33336
It seems like all your answers contain a link to that site. If it's spam, please stop. If it's not, sorry for the confusion, but I don't think that it's necessary to post a link in all your answers.
– Donald Duck
Mar 3 '17 at 12:43
1
Its tough to give an answer, where you can explain all scenarios. Like in this case, how to read json array or multiple json objects. Even If I do so, answer would be very long and person may get confuse. So I give a link where proper explanation is given, with proper example. He can chose to visit or can use only my explanation only.
– lalitbhagtani
Mar 3 '17 at 12:51
1
It appears to me that the link you have provided only demonstrates how to read JSON. Where can I find info on how to JSON as well?
– Lampros Tzanetos
Oct 27 '17 at 12:53
Sorry, but I didn't understand your question :- "on how to JSON as well"
– lalitbhagtani
Oct 31 '17 at 7:56
add a comment |
It seems like all your answers contain a link to that site. If it's spam, please stop. If it's not, sorry for the confusion, but I don't think that it's necessary to post a link in all your answers.
– Donald Duck
Mar 3 '17 at 12:43
1
Its tough to give an answer, where you can explain all scenarios. Like in this case, how to read json array or multiple json objects. Even If I do so, answer would be very long and person may get confuse. So I give a link where proper explanation is given, with proper example. He can chose to visit or can use only my explanation only.
– lalitbhagtani
Mar 3 '17 at 12:51
1
It appears to me that the link you have provided only demonstrates how to read JSON. Where can I find info on how to JSON as well?
– Lampros Tzanetos
Oct 27 '17 at 12:53
Sorry, but I didn't understand your question :- "on how to JSON as well"
– lalitbhagtani
Oct 31 '17 at 7:56
It seems like all your answers contain a link to that site. If it's spam, please stop. If it's not, sorry for the confusion, but I don't think that it's necessary to post a link in all your answers.
– Donald Duck
Mar 3 '17 at 12:43
It seems like all your answers contain a link to that site. If it's spam, please stop. If it's not, sorry for the confusion, but I don't think that it's necessary to post a link in all your answers.
– Donald Duck
Mar 3 '17 at 12:43
1
1
Its tough to give an answer, where you can explain all scenarios. Like in this case, how to read json array or multiple json objects. Even If I do so, answer would be very long and person may get confuse. So I give a link where proper explanation is given, with proper example. He can chose to visit or can use only my explanation only.
– lalitbhagtani
Mar 3 '17 at 12:51
Its tough to give an answer, where you can explain all scenarios. Like in this case, how to read json array or multiple json objects. Even If I do so, answer would be very long and person may get confuse. So I give a link where proper explanation is given, with proper example. He can chose to visit or can use only my explanation only.
– lalitbhagtani
Mar 3 '17 at 12:51
1
1
It appears to me that the link you have provided only demonstrates how to read JSON. Where can I find info on how to JSON as well?
– Lampros Tzanetos
Oct 27 '17 at 12:53
It appears to me that the link you have provided only demonstrates how to read JSON. Where can I find info on how to JSON as well?
– Lampros Tzanetos
Oct 27 '17 at 12:53
Sorry, but I didn't understand your question :- "on how to JSON as well"
– lalitbhagtani
Oct 31 '17 at 7:56
Sorry, but I didn't understand your question :- "on how to JSON as well"
– lalitbhagtani
Oct 31 '17 at 7:56
add a comment |
Gson is easy to learn and implement, what we need to know are following two methods
toJson() – Convert Java object to JSON format
fromJson() – Convert JSON into Java object
`
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();
}
}
}
`
For complete knowledge on Gson refer below links. github.com/google/gson/blob/master/UserGuide.md
– venkat
Feb 5 '16 at 6:24
add a comment |
Gson is easy to learn and implement, what we need to know are following two methods
toJson() – Convert Java object to JSON format
fromJson() – Convert JSON into Java object
`
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();
}
}
}
`
For complete knowledge on Gson refer below links. github.com/google/gson/blob/master/UserGuide.md
– venkat
Feb 5 '16 at 6:24
add a comment |
Gson is easy to learn and implement, what we need to know are following two methods
toJson() – Convert Java object to JSON format
fromJson() – Convert JSON into Java object
`
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();
}
}
}
`
Gson is easy to learn and implement, what we need to know are following two methods
toJson() – Convert Java object to JSON format
fromJson() – Convert JSON into Java object
`
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();
}
}
}
`
answered Feb 5 '16 at 6:19
venkatvenkat
385214
385214
For complete knowledge on Gson refer below links. github.com/google/gson/blob/master/UserGuide.md
– venkat
Feb 5 '16 at 6:24
add a comment |
For complete knowledge on Gson refer below links. github.com/google/gson/blob/master/UserGuide.md
– venkat
Feb 5 '16 at 6:24
For complete knowledge on Gson refer below links. github.com/google/gson/blob/master/UserGuide.md
– venkat
Feb 5 '16 at 6:24
For complete knowledge on Gson refer below links. github.com/google/gson/blob/master/UserGuide.md
– venkat
Feb 5 '16 at 6:24
add a comment |
You can use the Gson Library to parse the JSON string.
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();
You can also loop through the "posts" array as so:
JsonArray posts = jsonObject.getAsJsonArray("posts");
for (JsonElement post : posts) {
String postId = post.getAsJsonObject().get("post_id").getAsString();
//do something
}
add a comment |
You can use the Gson Library to parse the JSON string.
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();
You can also loop through the "posts" array as so:
JsonArray posts = jsonObject.getAsJsonArray("posts");
for (JsonElement post : posts) {
String postId = post.getAsJsonObject().get("post_id").getAsString();
//do something
}
add a comment |
You can use the Gson Library to parse the JSON string.
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();
You can also loop through the "posts" array as so:
JsonArray posts = jsonObject.getAsJsonArray("posts");
for (JsonElement post : posts) {
String postId = post.getAsJsonObject().get("post_id").getAsString();
//do something
}
You can use the Gson Library to parse the JSON string.
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();
You can also loop through the "posts" array as so:
JsonArray posts = jsonObject.getAsJsonArray("posts");
for (JsonElement post : posts) {
String postId = post.getAsJsonObject().get("post_id").getAsString();
//do something
}
answered Oct 19 '17 at 17:20
LittleBigUllahLittleBigUllah
11115
11115
add a comment |
add a comment |
Please do something like this:
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(contentString);
String product = (String) jsonObject.get("productId");
7
Er, which library is this?
– Stewart
Mar 19 '16 at 22:57
I think he is using org.json.simple
– Lasitha Yapa
Aug 23 '16 at 9:21
add a comment |
Please do something like this:
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(contentString);
String product = (String) jsonObject.get("productId");
7
Er, which library is this?
– Stewart
Mar 19 '16 at 22:57
I think he is using org.json.simple
– Lasitha Yapa
Aug 23 '16 at 9:21
add a comment |
Please do something like this:
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(contentString);
String product = (String) jsonObject.get("productId");
Please do something like this:
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(contentString);
String product = (String) jsonObject.get("productId");
edited Jul 14 '15 at 4:23
Pang
6,9321664102
6,9321664102
answered Jul 14 '15 at 4:14
SreekanthSreekanth
651
651
7
Er, which library is this?
– Stewart
Mar 19 '16 at 22:57
I think he is using org.json.simple
– Lasitha Yapa
Aug 23 '16 at 9:21
add a comment |
7
Er, which library is this?
– Stewart
Mar 19 '16 at 22:57
I think he is using org.json.simple
– Lasitha Yapa
Aug 23 '16 at 9:21
7
7
Er, which library is this?
– Stewart
Mar 19 '16 at 22:57
Er, which library is this?
– Stewart
Mar 19 '16 at 22:57
I think he is using org.json.simple
– Lasitha Yapa
Aug 23 '16 at 9:21
I think he is using org.json.simple
– Lasitha Yapa
Aug 23 '16 at 9:21
add a comment |
Top answers on this page use too simple examples like object with one property (e.g. {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 e.g. "Arbeit" using Google's Gson.
Two possible approaches:
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();
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;
add a comment |
Top answers on this page use too simple examples like object with one property (e.g. {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 e.g. "Arbeit" using Google's Gson.
Two possible approaches:
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();
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;
add a comment |
Top answers on this page use too simple examples like object with one property (e.g. {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 e.g. "Arbeit" using Google's Gson.
Two possible approaches:
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();
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;
Top answers on this page use too simple examples like object with one property (e.g. {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 e.g. "Arbeit" using Google's Gson.
Two possible approaches:
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();
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;
answered Jul 23 '16 at 14:46
yurinyurin
2,1212023
2,1212023
add a comment |
add a comment |
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/
Hope it helps!
You are pointing to version 1 of Jackson library. Strongly suggest to use current version of Jackson library.
– Herbert Yu
Aug 22 '17 at 0:58
add a comment |
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/
Hope it helps!
You are pointing to version 1 of Jackson library. Strongly suggest to use current version of Jackson library.
– Herbert Yu
Aug 22 '17 at 0:58
add a comment |
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/
Hope it helps!
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/
Hope it helps!
edited May 23 '17 at 12:34
Community♦
11
11
answered Nov 21 '16 at 12:05
Jose Manuel Gomez AlvarezJose Manuel Gomez Alvarez
860813
860813
You are pointing to version 1 of Jackson library. Strongly suggest to use current version of Jackson library.
– Herbert Yu
Aug 22 '17 at 0:58
add a comment |
You are pointing to version 1 of Jackson library. Strongly suggest to use current version of Jackson library.
– Herbert Yu
Aug 22 '17 at 0:58
You are pointing to version 1 of Jackson library. Strongly suggest to use current version of Jackson library.
– Herbert Yu
Aug 22 '17 at 0:58
You are pointing to version 1 of Jackson library. Strongly suggest to use current version of Jackson library.
– Herbert Yu
Aug 22 '17 at 0:58
add a comment |
Read the following blog post, JSON in Java.
This post is a little bit old, but still I want to answer you question.
Step 1: Create a POJO class of your data.
Step 2: Now create a object using JSON.
Employee employee = null;
ObjectMapper mapper = new ObjectMapper();
try{
employee = mapper.readValue(newFile("/home/sumit/employee.json"), Employee.class);
}
catch (JsonGenerationException e){
e.printStackTrace();
}
For further reference you can refer to the following link.
add a comment |
Read the following blog post, JSON in Java.
This post is a little bit old, but still I want to answer you question.
Step 1: Create a POJO class of your data.
Step 2: Now create a object using JSON.
Employee employee = null;
ObjectMapper mapper = new ObjectMapper();
try{
employee = mapper.readValue(newFile("/home/sumit/employee.json"), Employee.class);
}
catch (JsonGenerationException e){
e.printStackTrace();
}
For further reference you can refer to the following link.
add a comment |
Read the following blog post, JSON in Java.
This post is a little bit old, but still I want to answer you question.
Step 1: Create a POJO class of your data.
Step 2: Now create a object using JSON.
Employee employee = null;
ObjectMapper mapper = new ObjectMapper();
try{
employee = mapper.readValue(newFile("/home/sumit/employee.json"), Employee.class);
}
catch (JsonGenerationException e){
e.printStackTrace();
}
For further reference you can refer to the following link.
Read the following blog post, JSON in Java.
This post is a little bit old, but still I want to answer you question.
Step 1: Create a POJO class of your data.
Step 2: Now create a object using JSON.
Employee employee = null;
ObjectMapper mapper = new ObjectMapper();
try{
employee = mapper.readValue(newFile("/home/sumit/employee.json"), Employee.class);
}
catch (JsonGenerationException e){
e.printStackTrace();
}
For further reference you can refer to the following link.
edited Feb 4 '18 at 18:38
Peter Mortensen
13.7k1986112
13.7k1986112
answered Mar 22 '16 at 13:39
sumit kumarsumit kumar
3271522
3271522
add a comment |
add a comment |
You can use Jayway JsonPath. Below is a GitHub link with source code, pom details and good documentation.
https://github.com/jayway/JsonPath
Please follow the below steps.
Step 1: Add the jayway JSON path dependency in your class path using Maven or download the JAR file and manually add it.
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
Step 2: Please save your input JSON as a file for this example. In my case I saved your JSON as sampleJson.txt. Note you missed a comma between pageInfo and posts.
Step 3: Read the JSON contents from the above file using bufferedReader and save it as 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();
Step 4: Parse your JSON string using jayway JSON parser.
Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonInput);
Step 5: Read the details like below.
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);
The output will be:
$.pageInfo.pageName = abc
$.pageInfo.pagePic = http://example.com/content.jpg
$.posts[0].post_id = 123456789012_123456789012
add a comment |
You can use Jayway JsonPath. Below is a GitHub link with source code, pom details and good documentation.
https://github.com/jayway/JsonPath
Please follow the below steps.
Step 1: Add the jayway JSON path dependency in your class path using Maven or download the JAR file and manually add it.
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
Step 2: Please save your input JSON as a file for this example. In my case I saved your JSON as sampleJson.txt. Note you missed a comma between pageInfo and posts.
Step 3: Read the JSON contents from the above file using bufferedReader and save it as 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();
Step 4: Parse your JSON string using jayway JSON parser.
Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonInput);
Step 5: Read the details like below.
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);
The output will be:
$.pageInfo.pageName = abc
$.pageInfo.pagePic = http://example.com/content.jpg
$.posts[0].post_id = 123456789012_123456789012
add a comment |
You can use Jayway JsonPath. Below is a GitHub link with source code, pom details and good documentation.
https://github.com/jayway/JsonPath
Please follow the below steps.
Step 1: Add the jayway JSON path dependency in your class path using Maven or download the JAR file and manually add it.
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
Step 2: Please save your input JSON as a file for this example. In my case I saved your JSON as sampleJson.txt. Note you missed a comma between pageInfo and posts.
Step 3: Read the JSON contents from the above file using bufferedReader and save it as 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();
Step 4: Parse your JSON string using jayway JSON parser.
Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonInput);
Step 5: Read the details like below.
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);
The output will be:
$.pageInfo.pageName = abc
$.pageInfo.pagePic = http://example.com/content.jpg
$.posts[0].post_id = 123456789012_123456789012
You can use Jayway JsonPath. Below is a GitHub link with source code, pom details and good documentation.
https://github.com/jayway/JsonPath
Please follow the below steps.
Step 1: Add the jayway JSON path dependency in your class path using Maven or download the JAR file and manually add it.
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
Step 2: Please save your input JSON as a file for this example. In my case I saved your JSON as sampleJson.txt. Note you missed a comma between pageInfo and posts.
Step 3: Read the JSON contents from the above file using bufferedReader and save it as 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();
Step 4: Parse your JSON string using jayway JSON parser.
Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonInput);
Step 5: Read the details like below.
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);
The output will be:
$.pageInfo.pageName = abc
$.pageInfo.pagePic = http://example.com/content.jpg
$.posts[0].post_id = 123456789012_123456789012
edited Feb 4 '18 at 18:45
Peter Mortensen
13.7k1986112
13.7k1986112
answered Jul 26 '16 at 9:14
Ravi DurairajRavi Durairaj
51144
51144
add a comment |
add a comment |
{
"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
}
7
Please explain your answer as code-only answers help others far less than well documented code. See "give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime".
– Wai Ha Lee
Jul 28 '15 at 15:04
Would be good to mention this is for 'org.json' lib. However, I do not think this is a good way to do it at all being very verbose, and 'org.json' lib itself being obsolete (slow, cumbersome API). There are better choices: GSON, Jackson, Boon, Genson to use.
– StaxMan
Oct 6 '15 at 18:07
add a comment |
{
"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
}
7
Please explain your answer as code-only answers help others far less than well documented code. See "give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime".
– Wai Ha Lee
Jul 28 '15 at 15:04
Would be good to mention this is for 'org.json' lib. However, I do not think this is a good way to do it at all being very verbose, and 'org.json' lib itself being obsolete (slow, cumbersome API). There are better choices: GSON, Jackson, Boon, Genson to use.
– StaxMan
Oct 6 '15 at 18:07
add a comment |
{
"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
}
{
"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
}
answered Jul 28 '15 at 14:40
LReddyLReddy
871
871
7
Please explain your answer as code-only answers help others far less than well documented code. See "give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime".
– Wai Ha Lee
Jul 28 '15 at 15:04
Would be good to mention this is for 'org.json' lib. However, I do not think this is a good way to do it at all being very verbose, and 'org.json' lib itself being obsolete (slow, cumbersome API). There are better choices: GSON, Jackson, Boon, Genson to use.
– StaxMan
Oct 6 '15 at 18:07
add a comment |
7
Please explain your answer as code-only answers help others far less than well documented code. See "give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime".
– Wai Ha Lee
Jul 28 '15 at 15:04
Would be good to mention this is for 'org.json' lib. However, I do not think this is a good way to do it at all being very verbose, and 'org.json' lib itself being obsolete (slow, cumbersome API). There are better choices: GSON, Jackson, Boon, Genson to use.
– StaxMan
Oct 6 '15 at 18:07
7
7
Please explain your answer as code-only answers help others far less than well documented code. See "give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime".
– Wai Ha Lee
Jul 28 '15 at 15:04
Please explain your answer as code-only answers help others far less than well documented code. See "give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime".
– Wai Ha Lee
Jul 28 '15 at 15:04
Would be good to mention this is for 'org.json' lib. However, I do not think this is a good way to do it at all being very verbose, and 'org.json' lib itself being obsolete (slow, cumbersome API). There are better choices: GSON, Jackson, Boon, Genson to use.
– StaxMan
Oct 6 '15 at 18:07
Would be good to mention this is for 'org.json' lib. However, I do not think this is a good way to do it at all being very verbose, and 'org.json' lib itself being obsolete (slow, cumbersome API). There are better choices: GSON, Jackson, Boon, Genson to use.
– StaxMan
Oct 6 '15 at 18:07
add a comment |
I have JSON like this:
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
}
}
Java class
class PageInfo {
private String pageName;
private String pagePic;
// Getters and setters
}
Code for converting this JSON to a Java class.
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>
add a comment |
I have JSON like this:
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
}
}
Java class
class PageInfo {
private String pageName;
private String pagePic;
// Getters and setters
}
Code for converting this JSON to a Java class.
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>
add a comment |
I have JSON like this:
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
}
}
Java class
class PageInfo {
private String pageName;
private String pagePic;
// Getters and setters
}
Code for converting this JSON to a Java class.
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>
I have JSON like this:
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
}
}
Java class
class PageInfo {
private String pageName;
private String pagePic;
// Getters and setters
}
Code for converting this JSON to a Java class.
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>
edited Feb 4 '18 at 18:51
Peter Mortensen
13.7k1986112
13.7k1986112
answered Sep 16 '16 at 9:26
Parth SolankiParth Solanki
1,7071429
1,7071429
add a comment |
add a comment |
One can use Apache @Model annotation to create Java model classes representing structure of JSON files and use them to access various elements in the JSON tree. Unlike other solutions this one works completely without reflection and is thus suitable for environments where reflection is impossible or comes with significant overhead.
There is a sample Maven project showing the usage. First of all it defines the structure:
@Model(className="RepositoryInfo", properties = {
@Property(name = "id", type = int.class),
@Property(name = "name", type = String.class),
@Property(name = "owner", type = Owner.class),
@Property(name = "private", type = boolean.class),
})
final class RepositoryCntrl {
@Model(className = "Owner", properties = {
@Property(name = "login", type = String.class)
})
static final class OwnerCntrl {
}
}
and then it uses the generated RepositoryInfo and Owner classes to parse the provided input stream and pick certain information up while doing that:
List<RepositoryInfo> repositories = new ArrayList<>();
try (InputStream is = initializeStream(args)) {
Models.parse(CONTEXT, RepositoryInfo.class, is, repositories);
}
System.err.println("there is " + repositories.size() + " repositories");
repositories.stream().filter((repo) -> repo != null).forEach((repo) -> {
System.err.println("repository " + repo.getName() +
" is owned by " + repo.getOwner().getLogin()
);
})
That is it! In addition to that here is a live gist showing similar example together with asynchronous network communication.
add a comment |
One can use Apache @Model annotation to create Java model classes representing structure of JSON files and use them to access various elements in the JSON tree. Unlike other solutions this one works completely without reflection and is thus suitable for environments where reflection is impossible or comes with significant overhead.
There is a sample Maven project showing the usage. First of all it defines the structure:
@Model(className="RepositoryInfo", properties = {
@Property(name = "id", type = int.class),
@Property(name = "name", type = String.class),
@Property(name = "owner", type = Owner.class),
@Property(name = "private", type = boolean.class),
})
final class RepositoryCntrl {
@Model(className = "Owner", properties = {
@Property(name = "login", type = String.class)
})
static final class OwnerCntrl {
}
}
and then it uses the generated RepositoryInfo and Owner classes to parse the provided input stream and pick certain information up while doing that:
List<RepositoryInfo> repositories = new ArrayList<>();
try (InputStream is = initializeStream(args)) {
Models.parse(CONTEXT, RepositoryInfo.class, is, repositories);
}
System.err.println("there is " + repositories.size() + " repositories");
repositories.stream().filter((repo) -> repo != null).forEach((repo) -> {
System.err.println("repository " + repo.getName() +
" is owned by " + repo.getOwner().getLogin()
);
})
That is it! In addition to that here is a live gist showing similar example together with asynchronous network communication.
add a comment |
One can use Apache @Model annotation to create Java model classes representing structure of JSON files and use them to access various elements in the JSON tree. Unlike other solutions this one works completely without reflection and is thus suitable for environments where reflection is impossible or comes with significant overhead.
There is a sample Maven project showing the usage. First of all it defines the structure:
@Model(className="RepositoryInfo", properties = {
@Property(name = "id", type = int.class),
@Property(name = "name", type = String.class),
@Property(name = "owner", type = Owner.class),
@Property(name = "private", type = boolean.class),
})
final class RepositoryCntrl {
@Model(className = "Owner", properties = {
@Property(name = "login", type = String.class)
})
static final class OwnerCntrl {
}
}
and then it uses the generated RepositoryInfo and Owner classes to parse the provided input stream and pick certain information up while doing that:
List<RepositoryInfo> repositories = new ArrayList<>();
try (InputStream is = initializeStream(args)) {
Models.parse(CONTEXT, RepositoryInfo.class, is, repositories);
}
System.err.println("there is " + repositories.size() + " repositories");
repositories.stream().filter((repo) -> repo != null).forEach((repo) -> {
System.err.println("repository " + repo.getName() +
" is owned by " + repo.getOwner().getLogin()
);
})
That is it! In addition to that here is a live gist showing similar example together with asynchronous network communication.
One can use Apache @Model annotation to create Java model classes representing structure of JSON files and use them to access various elements in the JSON tree. Unlike other solutions this one works completely without reflection and is thus suitable for environments where reflection is impossible or comes with significant overhead.
There is a sample Maven project showing the usage. First of all it defines the structure:
@Model(className="RepositoryInfo", properties = {
@Property(name = "id", type = int.class),
@Property(name = "name", type = String.class),
@Property(name = "owner", type = Owner.class),
@Property(name = "private", type = boolean.class),
})
final class RepositoryCntrl {
@Model(className = "Owner", properties = {
@Property(name = "login", type = String.class)
})
static final class OwnerCntrl {
}
}
and then it uses the generated RepositoryInfo and Owner classes to parse the provided input stream and pick certain information up while doing that:
List<RepositoryInfo> repositories = new ArrayList<>();
try (InputStream is = initializeStream(args)) {
Models.parse(CONTEXT, RepositoryInfo.class, is, repositories);
}
System.err.println("there is " + repositories.size() + " repositories");
repositories.stream().filter((repo) -> repo != null).forEach((repo) -> {
System.err.println("repository " + repo.getName() +
" is owned by " + repo.getOwner().getLogin()
);
})
That is it! In addition to that here is a live gist showing similar example together with asynchronous network communication.
answered Nov 21 '17 at 7:43
Jaroslav TulachJaroslav Tulach
33925
33925
add a comment |
add a comment |
You can use JsonNode for a structured tree representation of your JSON string. It's part of the rock solid jackson library which is omnipresent.
ObjectMapper mapper = new ObjectMapper();
JsonNode yourObj = mapper.readTree("{"k":"v"}");
add a comment |
You can use JsonNode for a structured tree representation of your JSON string. It's part of the rock solid jackson library which is omnipresent.
ObjectMapper mapper = new ObjectMapper();
JsonNode yourObj = mapper.readTree("{"k":"v"}");
add a comment |
You can use JsonNode for a structured tree representation of your JSON string. It's part of the rock solid jackson library which is omnipresent.
ObjectMapper mapper = new ObjectMapper();
JsonNode yourObj = mapper.readTree("{"k":"v"}");
You can use JsonNode for a structured tree representation of your JSON string. It's part of the rock solid jackson library which is omnipresent.
ObjectMapper mapper = new ObjectMapper();
JsonNode yourObj = mapper.readTree("{"k":"v"}");
edited Feb 4 '18 at 18:56
Peter Mortensen
13.7k1986112
13.7k1986112
answered Feb 24 '17 at 5:56
slashronslashron
122211
122211
add a comment |
add a comment |
We can use the JSONObject class to convert a JSON string to a 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));
}
}
2
This is android only
– Ľubomír
May 5 '17 at 16:01
It's not just android: docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
– Dermot Canniffe
Sep 7 '17 at 9:47
1
@DermotCanniffe it is just Android.
– user4020527
Oct 28 '17 at 5:29
add a comment |
We can use the JSONObject class to convert a JSON string to a 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));
}
}
2
This is android only
– Ľubomír
May 5 '17 at 16:01
It's not just android: docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
– Dermot Canniffe
Sep 7 '17 at 9:47
1
@DermotCanniffe it is just Android.
– user4020527
Oct 28 '17 at 5:29
add a comment |
We can use the JSONObject class to convert a JSON string to a 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));
}
}
We can use the JSONObject class to convert a JSON string to a 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));
}
}
edited Feb 4 '18 at 19:01
Peter Mortensen
13.7k1986112
13.7k1986112
answered Apr 11 '17 at 12:24
smithsmith
191118
191118
2
This is android only
– Ľubomír
May 5 '17 at 16:01
It's not just android: docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
– Dermot Canniffe
Sep 7 '17 at 9:47
1
@DermotCanniffe it is just Android.
– user4020527
Oct 28 '17 at 5:29
add a comment |
2
This is android only
– Ľubomír
May 5 '17 at 16:01
It's not just android: docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
– Dermot Canniffe
Sep 7 '17 at 9:47
1
@DermotCanniffe it is just Android.
– user4020527
Oct 28 '17 at 5:29
2
2
This is android only
– Ľubomír
May 5 '17 at 16:01
This is android only
– Ľubomír
May 5 '17 at 16:01
It's not just android: docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
– Dermot Canniffe
Sep 7 '17 at 9:47
It's not just android: docs.oracle.com/javaee/7/api/javax/json/JsonObject.html
– Dermot Canniffe
Sep 7 '17 at 9:47
1
1
@DermotCanniffe it is just Android.
– user4020527
Oct 28 '17 at 5:29
@DermotCanniffe it is just Android.
– user4020527
Oct 28 '17 at 5:29
add a comment |
jsoniter (jsoniterator) is a relatively new and simple json library, designed to be simple and fast. All you need to do to deserialize json data is
JsonIterator.deserialize(jsonData, int.class);
where jsonData is a string of json data.
Check out the official website
for more information.
add a comment |
jsoniter (jsoniterator) is a relatively new and simple json library, designed to be simple and fast. All you need to do to deserialize json data is
JsonIterator.deserialize(jsonData, int.class);
where jsonData is a string of json data.
Check out the official website
for more information.
add a comment |
jsoniter (jsoniterator) is a relatively new and simple json library, designed to be simple and fast. All you need to do to deserialize json data is
JsonIterator.deserialize(jsonData, int.class);
where jsonData is a string of json data.
Check out the official website
for more information.
jsoniter (jsoniterator) is a relatively new and simple json library, designed to be simple and fast. All you need to do to deserialize json data is
JsonIterator.deserialize(jsonData, int.class);
where jsonData is a string of json data.
Check out the official website
for more information.
answered Oct 19 '18 at 0:48
Supa Mega Ducky Momo da WaffleSupa Mega Ducky Momo da Waffle
1
1
add a comment |
add a comment |
First of all this is not a valid json data.
You have to put a comma between the two json elements pageInfo and posts.
Here is the valid 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"
}
]
}
Now you may parse it using any of above described methods, or if you implement this library, then it is best.
add a comment |
First of all this is not a valid json data.
You have to put a comma between the two json elements pageInfo and posts.
Here is the valid 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"
}
]
}
Now you may parse it using any of above described methods, or if you implement this library, then it is best.
add a comment |
First of all this is not a valid json data.
You have to put a comma between the two json elements pageInfo and posts.
Here is the valid 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"
}
]
}
Now you may parse it using any of above described methods, or if you implement this library, then it is best.
First of all this is not a valid json data.
You have to put a comma between the two json elements pageInfo and posts.
Here is the valid 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"
}
]
}
Now you may parse it using any of above described methods, or if you implement this library, then it is best.
edited Oct 19 '18 at 1:10
Supa Mega Ducky Momo da Waffle
1
1
answered Sep 21 '18 at 18:05
NiravdasNiravdas
546
546
add a comment |
add a comment |
1 2
next
protected by Mena Jan 31 '18 at 16:55
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
6
java's built in JSON libraries are the quickets way to do so, but in my experience GSON is the best library for parsing a JSON into a POJO painlessly.
– Iman Akbari
Mar 9 '16 at 11:11
58
This question really was too broad and "write the code for me" which leads to a mess of confusing and differing answers below. This question should have been closed for being too broad and the author making no effort to solve it themselves, showing no homework.
– Jayson Minard
May 18 '16 at 12:57
10
This is the first highly voted and protected question whose answers I found the most confusing
– Riyafa Abdul Hameed
Jun 21 '17 at 6:48
6
@JaysonMinard agreed. Asked for mod intervention. This should be closed really. I initially assumed (wrongly) I couldn't do so while the question was protected, so I unprotected it and did my thing. Re-protected it now to prevent low rep answers and such like, while waiting for a mod.
– Mena
Jan 31 '18 at 16:59
5
This question is being discussed on Meta.
– Mark Amery
Feb 5 '18 at 12:34