How to parse JSON in Java
Asked Answered
B

37

1331

I have the following JSON text. How can I parse it to get the values of 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"
    }
  ]
}
Browse answered 7/4, 2010 at 9:0 Comment(10)
androidbeasts.wordpress.com/2015/08/04/json-parsing-tutorial : try thisSearch
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.Proffer
There are many notorious java libraries in java: jackson, gson, org.json, genson, etc. Choosing one should take into account their relative performance and feature set. Here is a benchmark did using JMH that compares the performance of the most popular json libraries in java: github.com/fabienrenaud/java-json-benchmark. See my post below for some more info.Betaine
use Gson github.com/google/gsonCock
@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.Natascha
This question is being discussed on Meta.Sanctuary
@ImanAkbari What JSON library is built-in? I found Java Specification Request 353 but that just specifies what objects should exist, it is not an implementation. Something generic-sounding like org.json is also third party (and unmaintained, it seems). Which libraries are you talking about?Genevagenevan
@Genevagenevan you are right, my bad. I meant org.json they are all 3rd party.Proffer
Most people confuses between parsing and map. Mapping is really wasy, you can use Gjson, Jackson and others. But, parsing is a different thing. You can use reg exps and such complex techniques. For parsing I would go with something like JsonPath.Towards
@Genevagenevan There are two JSON standard APIs in JakartaEE: Jakarta JSON Processing API and Jakarta JSON Binding API (based on the former).Ibeam
P
956

The org.json library is easy to use.

Just remember (while casting or using methods like getJSONObject and getJSONArray) that in JSON notation

  • [ … ] represents an array, so library will parse it to JSONArray
  • { … } represents an object, so library will parse it to JSONObject

Example code below:

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
}

You may find more examples from: Parse JSON in Java

Downloadable jar: http://mvnrepository.com/artifact/org.json/json

Pycnidium answered 25/9, 2013 at 6:56 Comment(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.Mckoy
@Bloodthirsty 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.Hip
@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.Bloodthirsty
I agree with you @StaxMan, may be I'm just a big fan of Crockford.Hip
@user1156544 Well technically JSON was invented by many people including JavaScript and Python authors. But the term JSON was coined by Douglas Crockford, and he popularized JSON as a date exchange format instead of XML so, he actually discovered JSON as a data exchange format: youtube.com/watch?v=kc8BAR7SHJIHip
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.Betaine
Extremely inconvenient, it even does not support de/serialization.Aberrant
The License doesn't include any commonly used Open Source licensing, and it also holds copyrights.Retirement
org.json is extremely slow compared to Jackson https://mcmap.net/q/11375/-how-to-parse-json-in-javaZayas
what's the command to install this?Richardricharda
T
698

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

Jackson (Maven)

My personal favourite and probably the most widely used.

ObjectMapper mapper = new ObjectMapper();

// De-serialize to an object
Person user = mapper.readValue("{\"name\": \"John\"}", Person.class);
System.out.println(user.name); //John

// Read a single attribute
JsonNode nameNode = mapper.readTree("{\"name\": \"John\"}");
System.out.println(nameNode.get("name").asText());

Google GSON (Maven)

Gson g = new Gson();

// De-serialize to an object
Person person = g.fromJson("{\"name\": \"John\"}", Person.class);
System.out.println(person.name); //John

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

Org.JSON (Maven)

This suggestion is listed here simply because it appears to be quite popular due to stackoverflow reference to it. I would not recommend using it as it is more a proof-of-concept project than an actual library.

JSONObject obj = new JSONObject("{\"name\": \"John\"}");

System.out.println(obj.getString("name")); //John
Tighten answered 31/7, 2015 at 9:54 Comment(8)
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.Bloodthirsty
Two other libraries worth mentioning (in the interest of completeness): json-simple and Oracle's JSONPBarong
@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.Morly
json-simple and oracle's jsonp perform terribly: github.com/fabienrenaud/java-json-benchmark For performance, choose jackson or dsljson.Betaine
GSON does not support dynamic filtering of fields on levels other than root!Aberrant
why does Google try to impose everything theirs as the best? And, more importantly, why does everyone buy into their cohones?Briton
Note: It's essential that the 'name' variable is public. Otherwise your result is null.Lothar
For GSON I note (your example) that new JsonParser().parse() is deprecated (v2.8.6+) - see https://mcmap.net/q/21224/-jsonparser-is-deprecated for alternative usage of JsonParser.parseString()Homolographic
S
116
  1. 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);
    
  2. 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");
    
Schurman answered 18/2, 2015 at 23:34 Comment(3)
@Schurman 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.Chromato
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.Bloodthirsty
I suggest adding a link to the JavaEE library.Glaikit
F
81

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);
Fiorenze answered 24/2, 2013 at 6:24 Comment(8)
Is there a javadoc available?Rightwards
This package cannot handle empty values when parsing. For example: ... "description":"" ... throws an ExceptionLiberal
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.Transom
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.Bloodthirsty
I just tried version 1.0.4 and it seems to have quite a few bugs regarding parsing arrays (empty arrays as well as arrays of objects)Cosgrave
This project appears to be dead and appears to be no longer hosted in the central Maven repository.Unheard
Also, it reports numbers as strings. That, along with the empty string issue, was a deal-breaker for me. Downvoted.Bainbrudge
So, instead of having deserialized object, we have a map. Sometimes it can be useful.Aberrant
E
57

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.

JSON

From your example:

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

Parsing

Now you can parse using Gson library:

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

Gradle import

Remember to import the library in the app Gradle file

implementation 'com.google.code.gson:gson:2.8.6' // or earlier versions

Automatic model generation

You can generate model from JSON automatically using online tools like this.

Edgewise answered 1/6, 2016 at 15:20 Comment(0)
M
47

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
Mineraloid answered 12/7, 2016 at 19:6 Comment(1)
any support JDK version?Condemnatory
V
46

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.

Vanbuskirk answered 16/12, 2015 at 13:51 Comment(1)
This a very good library especially for reading and updating JSON but beware of some known issue about this library. See [1]: github.com/json-path/JsonPath/issues/272 [2]: github.com/json-path/JsonPath/issues/375Orfurd
M
32

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>
Mockup answered 15/8, 2016 at 19:57 Comment(2)
How does the pojo will look?Misstep
For Pojo use gson. This library doesn't support.Mockup
C
27

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.

Castera answered 2/5, 2016 at 21:58 Comment(0)
Z
24

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.

Zayas answered 8/2, 2017 at 7:9 Comment(6)
What is the unit """? Not inches? Is it seconds? Minutes?Galloway
@PeterMortensen it means seconds. Since it seems unclear I'll change it. Thanks for the review.Zayas
Unfortunately, Nashorn is deprecated in Java 11. JEP 335.Ramonramona
I know Nashorn is deprecated, but I liked this answer because I didn't want any dependencies; however, I had to re-work the example a bit: ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript"); engine.eval("var fun = function(raw) { return JSON.parse(raw); };"); Map<String, Object> json = (Map<String, Object>) ((Invocable) engine).invokeFunction("fun", jsonString);Haye
@Haye Awesome! Do you know how to access array elements from the Objects returned? The class is ScriptObjectMirror but it's not accessible...Maybe
@Haye Found it: cast to javax.script.Bindings that is a Map<String,Object>.Maybe
T
23

I believe the best practice should be to go through the official Java JSON API which are still work in progress.

Tricho answered 8/4, 2013 at 17:37 Comment(5)
Since I replied, I started using Jackson and I think it's one of the best libraries out there for JSON de-serialization.Tricho
Why do they re-use JSONP to mean something different than JSON with Padding?...Pia
@ChrisWesseling What do you mean?Tricho
"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.Pia
@ChrisWesseling oh that is confusing. That's what they chose for the specification. However as I said, I would go straight to Jackson.Tricho
B
13

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:

  1. Performance
  2. Ease of use (code is simple to write and legible) - that goes with features.
  3. 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.

Betaine answered 27/6, 2016 at 20:32 Comment(0)
A
12

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.

Ader answered 15/5, 2014 at 1:56 Comment(3)
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.Karrah
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)Bloodthirsty
Or does brainmurphy1 mean JSONArray in Android?Ilario
D
12

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;
}
Dorn answered 16/12, 2015 at 21:23 Comment(0)
D
9

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.

Downbow answered 29/8, 2015 at 12:39 Comment(0)
M
9

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

    }
}

`

Mychal answered 5/2, 2016 at 6:19 Comment(1)
For complete knowledge on Gson refer below links. github.com/google/gson/blob/master/UserGuide.mdMychal
K
9

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

Kinesiology answered 3/3, 2017 at 12:17 Comment(4)
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.Benco
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.Kinesiology
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?Derogatory
Sorry, but I didn't understand your question :- "on how to JSON as well"Kinesiology
R
7

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.

Rightful answered 22/3, 2016 at 13:39 Comment(0)
F
7

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
}
Foveola answered 19/10, 2017 at 17:20 Comment(0)
U
6

Please do something like this:

JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(contentString);
String product = (String) jsonObject.get("productId");
Unequal answered 14/7, 2015 at 4:14 Comment(3)
Er, which library is this?Tribalism
I think he is using org.json.simpleIllegalize
in the last line supposed to ne String product = (String) obj.get("productId");Boehm
T
6
{
   "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
}
Triennial answered 28/7, 2015 at 14:40 Comment(2)
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".Sodamide
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.Bloodthirsty
P
6

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
Pomatum answered 26/7, 2016 at 9:14 Comment(0)
M
6

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>
Mission answered 16/9, 2016 at 9:26 Comment(0)
P
6

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!

Piscina answered 21/11, 2016 at 12:5 Comment(1)
You are pointing to version 1 of Jackson library. Strongly suggest to use current version of Jackson library.Stylet
B
5

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:

  1. Retrieve just one needed attribute

     String json  = callToTranslateApi("work", "de");
     JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
     return jsonObject.get("data").getAsJsonObject()
             .get("translations").getAsJsonArray()
             .get(0).getAsJsonObject()
             .get("translatedText").getAsString();
    
  2. Create Java object from JSON

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

    ...

      Gson g = new Gson();
      String json =callToTranslateApi("work", "de");
      ApiResponse response = g.fromJson(json, ApiResponse.class);
      return response.data.translations[0].translatedText;
    
Bedraggled answered 23/7, 2016 at 14:46 Comment(0)
N
5

Any kind of json array steps to solve the issue.

  1. Convert your JSON object to a java object.
  2. You can use this link or any online tool.
  3. Save out as a java class like Myclass.java.
  4. Myclass obj = new Gson().fromJson(JsonStr, Myclass.class);
  5. Using obj, you can get your values.
Nyctaginaceous answered 12/2, 2022 at 9:49 Comment(0)
S
3

If you have maven project then add below dependency or normal project add json-simple jar.

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20180813</version>
</dependency>

Write below java code for convert JSON string to JSON array.

JSONArray ja = new JSONArray(String jsonString);
Swope answered 8/7, 2020 at 5:8 Comment(0)
B
2

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.

Bridgework answered 21/11, 2017 at 7:43 Comment(0)
R
2

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.

Rom answered 19/10, 2018 at 0:48 Comment(0)
F
2

Jakarta (Java) Enterprise Edition 8 includes the JSON-B (Java API for JSON Binding). So, if you are using a Jakarta EE 8 server, like Payara 5, JSON-B will be available out of the box.

A simple example, without custom configuration:

public static class Dog {
    public String name;
    public int age;
    public boolean bites;
}

// Create a dog instance
Dog dog = new Dog();
dog.name = "Falco";
dog.age = 4;
dog.bites = false;

// Create Jsonb and serialize
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(dog);

// Deserialize back
dog = jsonb.fromJson("{\"name\":\"Falco\",\"age\":4,\"bites\":false}", Dog.class);

You can customize the mapping by using configuration, annotations, adapters and (de)serializers.

If you are not using a Jakarta EE 8 use can always install JSON-B.

Furlong answered 2/5, 2020 at 16:37 Comment(1)
This should be the accepted answer. JSON-B is a Java/Jakarta standarad. Jackson Databind has had security vulnerabilities.Astylar
J
2

If your data is simple and you don't want external dependencies, use some lines of code:

/**
 * A very simple JSON parser for one level, everything quoted.
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, String> simpleParseJson(String json) {
    Map<String, String> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\", "\\").split("\"");
    for (int i = 1; i + 3 < qs.length; i += 4) {
        map.put(qs[i].replace('\u0001', '"'), qs[i + 2].replace('\u0001', '"'));
    }
    return map;
}

So this data

{"name":"John", "age":"30", "car":"a \"quoted\" back\\slash car"}

yields a map containing

{age=30, car=a "quoted" back\slash car, name=John}

This can be upgraded to work with unquoted values too...

/**
 * A very simple JSON parser for one level, names are quoted.
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, String> simpleParseJson(String json) {
    Map<String, String> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\",  "\\").split("\"");
    for (int i = 1; i + 1 < qs.length; i += 4) {
        if (qs[i + 1].trim().length() > 1) {
            String x = qs[i + 1].trim();
            map.put(qs[i].replace('\u0001', '"'), x.substring(1, x.length() - 1).trim().replace('\u0001', '"'));
            i -= 2;
        } else {
            map.put(qs[i].replace('\u0001', '"'), qs[i + 2].replace('\u0001', '"'));
        }
    }
    return map;
}

And to solve complex structure, it gets ugly... ... SORRY!!! ... but I could not resist to code it^^ This parses the given JSON in question and way more. It yields nested maps and lists.

/**
 * A very simple JSON parser, names are quoted.
 * 
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, Object> simpleParseJson(String json) {
    Map<String, Object> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\", "\\").split("\"");
    int index[] = { 1 };
    recurse(index, map, qs);
    return map;
}

/**
 * Eierlegende Wollmilchsau.
 * 
 * @param index index into array.
 * @param map   the current map to fill.
 * @param qs    the data.
 */
private static void recurse(int[] index, Map<String, Object> map, String[] qs) {
    int i = index[0];
    for (;; i += 4) {
        String end = qs[i - 1].trim(); // check for termination of an object
        if (end.startsWith("}")) {
            qs[i - 1] = end.substring(1).trim();
            i -= 4;
            break;
        }

        String key = qs[i].replace('\u0001', '"');
        String x = qs[i + 1].trim();
        if (x.endsWith("{")) {
            x = x.substring(0, x.length() - 1).trim();
            if (x.endsWith("[")) {
                List<Object> list = new ArrayList<>();
                index[0] = i + 2;
                for (;;) {
                    Map<String, Object> inner = new TreeMap<>();
                    list.add(inner);
                    recurse(index, inner, qs);
                    map.put(key, list);
                    i = index[0];

                    String y = qs[i + 3]; // check for termination of array
                    if (y.startsWith("]")) {
                        qs[i + 3] = y.substring(1).trim();
                        break;
                    }
                }
                continue;
            }

            Map<String, Object> inner = new TreeMap<>();
            index[0] = i + 2;
            recurse(index, inner, qs);
            map.put(key, inner);
            i = index[0];
            continue;
        }
        if (x.length() > 1) { // unquoted
            String value = x.substring(1, x.length() - 1).trim().replace('\u0001', '"');
            if ("[]".equals(value)) // handle empty array
                map.put(key, new ArrayList<>());
            else
                map.put(key, value);
            i -= 2;
        } else {
            map.put(key, qs[i + 2].replace('\u0001', '"'));
        }
    }
    index[0] = i;
}

yields - if you print the map:

{pageInfo={pageName=abc, pagePic=http://example.com/content.jpg}, posts=[{actor_id=1234567890, comments=[], likesCount=2, message=Sounds cool. Can't wait to see it!, nameOfPersonWhoPosted=Jane Doe, picOfPersonWhoPosted=http://example.com/photo.jpg, post_id=123456789012_123456789012, timeOfPost=1234567890}]}
Jauregui answered 7/2, 2022 at 14:29 Comment(0)
M
1

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\"}");
Moorman answered 24/2, 2017 at 5:56 Comment(0)
P
1

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));
  }
}
Pharyngoscope answered 11/4, 2017 at 12:24 Comment(3)
This is android onlyPeraea
It's not just android: docs.oracle.com/javaee/7/api/javax/json/JsonObject.htmlPejorative
@DermotCanniffe it is just Android.Ambagious
N
1

You can use DSM stream parsing library for parsing complex json and XML document. DSM parse data only once and not load all data into memory.

Let's say we have Page class to deserialize given json data.

Page class

public class Page {
    private String pageName;
    private String pageImage;
    private List<Sting> postIds;

    // getter/setter

}

Create a yaml Mapping file.

result:
  type: object     # result is array
  path: /posts
  fields:
    pageName:
        path: /pageInfo/pageName
    pageImage:
        path: /pageInfo/pagePic
    postIds:
      path: post_id
      type: array

Use DSM to extract fields.

DSM dsm=new DSMBuilder(new File("path-to-yaml-config.yaml")).create(Page.class);
Page page= (Page)dsm.toObject(new path-to-json-data.json");

page variable serialized to json:

{
  "pageName" : "abc",
  "pageImage" : "http://example.com/content.jpg",
  "postIds" : [ "123456789012_123456789012" ]
}

DSM is very good for complex json and xml.

Nurseryman answered 30/3, 2019 at 15:42 Comment(0)
C
0

You need to use JsonNode and ObjectMapper class from the jackson library to fetch the nodes of your Json tree.Add the below dependency in your pom.xml to get an access to the Jackson classes.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.5</version>
</dependency>

You shall give a try on the below code, this would work :

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

class JsonNodeExtractor{

    public void convertToJson(){

        String filepath = "c:\\data.json";
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node =  mapper.readTree(filepath);

        // create a JsonNode for every root or subroot element in the Json String
        JsonNode pageInfoRoot = node.path("pageInfo");

        // Fetching elements under 'pageInfo'
        String pageName =  pageInfoRoot.path("pageName").asText();
        String pagePic = pageInfoRoot.path("pagePic").asText();

        // Now fetching elements under posts
        JsonNode  postsNode = node.path("posts");
        String post_id = postsNode .path("post_id").asText();
        String nameOfPersonWhoPosted = postsNode 
        .path("nameOfPersonWhoPosted").asText();
    }
}
Cicely answered 17/5, 2018 at 9:34 Comment(4)
How can you parse the json objects without reading from a file?Coccyx
@Coccyx : If you have a raw json to parse, then you can you can define a corresponding Pojo for the json.Cicely
Hi @Akash , I have corresponding getters and setters classes but I get null values. Would you mind sharing a piece of code for that?Coccyx
sure! @Coccyx String mobileJson = "{ \"brand\" : \"Apple\", \"Price\" : 1000 }"; //use the Reader Object Reader reader = new StringReader(mobileJson); ObjectMapper mapper = new ObjectMapper(); Mobile mobile =mapper.readValue(reader, Mobile.class);Cicely
C
0

There are 2 main options...

  1. Object mapping. When you deserialize JSON data to a number of instances of:

    1.1. Some predefined classes, like Maps. In this case, you don't have to design your own POJO classes. Some libraries: org.json.simple https://www.mkyong.com/java/json-simple-example-read-and-write-json/

    1.2. Your own POJO classes. You have to design your own POJO classes to present JSON data, but this may be helpful if you are going to use them into your business logic as well. Some libraries: Gson, Jackson (see http://tutorials.jenkov.com/java-json/index.html)

The main backwards of the mapping is that it leads to intensive memory allocation (and GC pressure) and CPU utilization.

  1. Stream oriented parsing. For example, both Gson and Jackson support such lightweight parsing. Also, you can take a look at an example of custom, fast and GC-free parser https://github.com/anatolygudkov/green-jelly. Prefer this way in case you need to parse a lot of data and in latency sensitivity applications.
Crum answered 4/12, 2019 at 13:47 Comment(0)
X
0

First, convert JSON to Java pojo using 'https://json2csharp.com/code-converters/json-to-pojo'tool or similar online tools.

"Remember - The POJOs in java are useful in defining objects to increase their readability and reusability."

After converting JSON to Java POJO:

public class Root{
    public PageInfo pageInfo;
    public List<Post> posts;
    //Getter Setter Methods
}
public class Post{
    public String post_id;
    public String actor_id;
    public String picOfPersonWhoPosted;
    public String nameOfPersonWhoPosted;
    public String message;
    public String likesCount;
    public List<Object> comments;
    public String timeOfPost;
    //Getter Setter Methods
}
public class PageInfo{
    public String pageName;
    public String pagePic;
    //Getter Setter Methods
}

Six different Java libraries for JSON serialization and deserialization are listed below:

  1. Jackson - Jackson dependency
  2. Gson - Gson dependency
  3. Moshi - Moshi dependency
  4. Genson - Genson dependency
  5. FastJson - FastJson dependency
  6. JSON-Java - JSON-Java dependency

Program

        // Using Jackson
        ObjectMapper objectMapper = new ObjectMapper();
        Root root1 = objectMapper.readValue(jsonText, Root.class);
        System.out.println(root1.posts.get(0).getActor_id());

        // Using Gson
        Gson gson = new Gson();
        Root root2 = gson.fromJson(jsonText, Root.class);
        System.out.println(root2.posts.get(0).getActor_id());

        // Using Moshi
        Moshi moshi = new Moshi.Builder().build();
        JsonAdapter<Root> jsonAdapter = moshi.adapter(Root.class);
        Root root3 = jsonAdapter.fromJson(jsonText);
        System.out.println(root3.posts.get(0).getActor_id());

        // Using Genson
        Root root4 = new Genson().deserialize(jsonText, Root.class);
        System.out.println(root4.posts.get(0).getActor_id());

        // Using FastJson
        Root root5 = JSON.parseObject(jsonText, Root.class);
        System.out.println(root5.posts.get(0).getActor_id());

        //Using JSON-Java
        JSONObject jsonObject = new JSONObject(jsonText);
        System.out.println(jsonObject.getJSONArray("posts").getJSONObject(0).get("actor_id"));

   
Xanthin answered 11/12, 2023 at 18:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.