Home java How and with what to parse Json in Java?

How and with what to parse Json in Java?

Author

Date

Category

There is often a need to work with Json , in particular to read and parse it. In Java you usually know what type of variables you are working with, but when parsing Json it is confusing that the type of fields can be any.

What are the ways to parse Json ? How to do it?

Here’s how to get data from the Json below?

{
  "firstName": "Json",
  "lastName": "Smith",
  "age": 30,
  "address": {
    "streetAddress": "666 1nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": 10021
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "542 666-1234"
    },
    {
      "type": "fax",
      "number": "653 666-4567"
    }
  ],
  "friends": [
    {
      "firstName": "Test",
      "lastName": "Snow",
      "age": 20,
      "phoneNumbers": [
        {
          "type": "home",
          "number": "141 111-1234"
        }
      ],
      "friends": [
        {
          "firstName": "UnknownFirstName",
          "lastName": "UnknownLastName",
          "age": 999,
          "phoneNumbers": [
            {
              "type": "home",
              "number": "000 000-0000"
            }
          ]
        }
      ]
    },
    {
      "firstName": "Flash",
      "lastName": "Tompson",
      "age": 23,
      "phoneNumbers": [
        {
          "type": "home",
"number": "999 111-1234"
        }
      ]
    }
  ]
}

Answer 1, authority 100%

You can get data in different ways and, of course, depends on the tasks. I’ll try to consider some options for parsing Json .

Note: for each of the examples for parsing, Json will be taken from the question, so as not to copy in vain in the answer.


Simple Json

Where to get it: here / github repository / or via Maven etc.

This is the most primitive way. Basically, all there is is JSONObject and JSONArray .

  • JSONArray can include multiple JSONObject , it can be looped through each iteration to get a JSONObject .
  • JSONObject is an object from which you can get its individual properties.

I would use it for small Json lines where you don’t have to bother too much or if you are not too lazy to write your own handler class based on the code shown below:

// Read json
Object obj = new JSONParser (). Parse (jsonString); // Object obj = new JSONParser (). Parse (new FileReader ("JSONExample.json"));
// Cast obj to JSONObject
JSONObject jo = (JSONObject) obj;
// Get firstName and lastName
String firstName = (String) jo.get ("firstName");
String lastName = (String) jo.get ("lastName");
System.out.println ("fio:" + firstName + "" + lastName);
// Get an array of numbers
JSONArray phoneNumbersArr = (JSONArray) jo.get ("phoneNumbers");
Iterator phonesItr = phoneNumbersArr.iterator ();
System.out.println ("phoneNumbers:");
// Print array data in a loop
while (phonesItr.hasNext ()) {
  JSONObject test = (JSONObject) phonesItr.next ();
  System.out.println ("- type:" + test.get ("type") + ", phone:" + test.get ("number"));
}

The rest of the work with nested arrays is similar. Can be added to List, Map, etc.


GSON

Where to get it: here / github repository / or via Maven etc.

Documentation: http: // www.studytrails.com/java/json/java-google-json-introduction/

Allows to parse Json as well as Json-simple , i.e. using JSONObject and JSONArray (see documentation ), but has a more powerful parsing tool.
It is enough to create classes that repeat the structure of Json ‘a. To parse Json from the question, create classes:

class Person {
  public String firstName;
  public String lastName;
  public int age;
  public Address address;
  public List & lt; Phones & gt; phoneNumbers;
  public List & lt; Person & gt; friends;
}
class Address {
  public String streetAddress;
  public String city;
  public String state;
  public int postalCode;
}
class Phones {
  public String type;
  public String number;
}

Now it’s enough to write:

Gson g = new Gson ();
Person person = g.fromJson (jsonString, Person.class);

That’s it! Magic! Miracle! Now person contains an object of type Person , which contains data of exactly the types that were specified in the created classes!
Now you can work with any type, as you used to always do: String, Integer, List, Map and everything else.

// Display the last names of all friends with their phones
for (Person friend: person.friends) {
  System.out.print (friend.lastName);
  for (Phones phone: friend.phoneNumbers) {
    System.out.println ("- phone type:" + phone.type + ", phone number:" + phone.number);
  }
}
// output:
// Snow - phone type: home, phone number: 141 111-1234
// Tompson - phone type: home, phone number: 999 111-1234

Example of parsing in Map :

…… JSON to parse:


Answer 2, authority 13%

Some more options


LoganSquare

LoganSquare – Based on Jackson ‘s streaming API. demo tests runs faster GSON and Jackson . So good for Android.

Where to get it: github repository / or via Maven / Gradle etc.

Usage: https://github.com/bluelinelabs/LoganSquare# usage

A simple example:

@ JsonObject
public class Person {
  @JsonField (name = "firstName")
  public String firstName;
  @JsonField (name = "age")
  public int age;
  public void say () {
    System.out.println ();
    System.out.println ("My name is" + firstName + ", I'm" + age + "years old!");
  }
}

parsing:

String jsonString = "{\" age \ ": 15, \" firstName \ ": \" Adam \ " } ";
Person person = LoganSquare.parse (jsonString, Person.class);
person.say (); // My name is Adam, I'm 18 years old!

Moshi

Moshi is a modern JSON library for Android and Java.

Good, according to the developers, for working with Android.

Where to get it: github repository / or via Maven / Gradle etc.

  • An example of parsing a Json string into a Person object:

    Moshi moshi = new Moshi.Builder (). build ();
    JsonAdapter & lt; Person & gt; jsonAdapter = moshi.adapter (Person.class);
    Person person = jsonAdapter.fromJson (jsonStringPerson); // person will contain all data
    
  • Example of parsing in Map :

    class Seanse {
      public String name;
      public String locate
      public String metro;
      public List & lt; Sessions & gt; sessions;
    }
    class Sessions {
      public String time;
      public double price;
    }
    public class Main {
      public static void main (String [] args) throws IOException {
        String jsonStringForMap = "{\" 2 \ ": {\" sessions \ ": [{\" time \ ": \" 13:00 \ ", \" price \ ": \" 410 \ "}, {\" time \ ": \" 06:40 \ ", \" price \ ": \" 340 \ "}, {\" time \ ": \" 16:50 \ ", \" price \ ": \" 370 \ "}], \" name \ ": \" Kinokis-L \ ", \" locate \ ": \" Moscow, Sadovaya-Spasskaya street, 21, 56 \ ", \" metro \ ": \" Red gate \ "}, \" 7 \ ": {\" sessions \ ": [{\" time \ ": \" 06:35 \ ", \" price \ ": \" 190 \ "}, {\" time \ ": \" 00:05 \ ", \" price \ ": \" 410 \ "}], \" name \ ": \" Kinokis-V \ ", \" locate \ ": \" Paveletskaya pl. , 2, building 1 \ ", \" metro \ ": \" Paveletskaya \ "}, \" 8 \ ": {\" sessions \ ": [{\" time \ ": \" 15: 10 \ ", \ "price \": \ "330 \"}], \ "name \": \ "Kinokis-J \", \ "locate \": \ "st. Prechistenka, 40/2 \ ", \" metro \ ": \" Kropotkinskaya \ "}, \" 9 \ ": {\" sessions \ ": [{\" time \ ": \" 13: 00 \ ", \ "price \": \ "600 \"}, {\ "time \": \ "08:30 \", \ "price \": \ "300 \"}, {\ "time \": \ " 04:00 \ ", \" price \ ": \" 510 \ "}, {\" time \ ": \" 13:15 \ ", \" price \ ": \" 340 \ "}], \" name \ ": \" Kinokis-U \ ", \" locate \ ": \" 24 Sharikopodshipnikovskaya str. \ ", \" metro \ ": \" Dubrovka \ "}}";
        Moshi moshi = new Moshi.Builder (). Build ();
        Type map = Types.newParameterizedType (Map.class, String.class, Seanse.class);
        JsonAdapter & lt; Map & lt; String, Seanse & gt; & gt; jsonAdapter = moshi.adapter (map);
        Map & lt; String, Seanse & gt; seanseMap = jsonAdapter.fromJson (jsonStringForMap);
      }
    }
    

Genson

Where to get it: here / github repository / or via Maven etc.

Documentation: http://owlike.github.io / genson / Documentation / UserGuide /

By creating a POJO (classes are created that repeat the structure of Json ‘a) – an object is parsed from a string, pushing it into the required fields of objects. It is possible to filter properties, include or exclude fields when parsing,
rename, the ability to work with annotations, etc. Read more in the documentation.

  • Simple parsing:

    Genson genson = new Genson ();
    Person person = genson.deserialize (jsonString, Person.class); // person will contain all data
    
  • Parse to list:

    List & lt; Object & gt; persons = genson.deserialize ("[{\" age \ ": 28, \" name \ ": \" Foo \ "}, {\" age \ ": 30, \" name \ ": \" Bar \ " }] ", List.class);
    // persons - a list with object data
    
  • Example of parsing in Map :

…… JSON to parse:


Answer 3, authority 9%

JSON-P

Supports JSON serialization and parsing without preliminary mapping in classes:

Maven:

& lt; dependency & gt;
  & lt; groupId & gt; javax.json & lt; / groupId & gt;
  & lt; artifactId & gt; javax.json-api & lt; / artifactId & gt;
  & lt; version & gt; 1.1.2 & lt; / version & gt;
& lt; / dependency & gt;
& lt; dependency & gt;
  & lt; groupId & gt; org.glassfish & lt; / groupId & gt;
  & lt; artifactId & gt; javax.json & lt; / artifactId & gt;
  & lt; version & gt; 1.1.2 & lt; / version & gt;
& lt; / dependency & gt;

An example of parsing a JSON string:

public static void main (String [] args) throws IOException {
  JsonReader reader = Json.createReader (new StringReader (jsonString));
  JsonObject jsonObject = reader.readObject ();
}

An example of outputting an object to a JSON string:

public static void main (String [] args) throws IOException {
  System.out.println (prettyPrintJson (jsonObject, 0));
}
public static String prettyPrintJson (JsonObject jsonObject, int indent) {
  String indentStr = getIndentStr (indent);
  String prettyJson = indentStr + "{";
  for (String key: jsonObject.keySet ()) {
    prettyJson + = "\ n";
    prettyJson + = indentStr + "\" "+ key +" \ ":";
    try {
      JsonArray jsonArray = jsonObject.get (key) .asJsonArray ();
      prettyJson + = "\ n" + indentStr + "[";
      for (JsonValue element: jsonArray) {
        prettyJson + = "\ n" + prettyPrintJson (element.asJsonObject (), indent + 4);
        prettyJson + = ",";
      }
      prettyJson = prettyJson.substring (0, prettyJson.length () - 1);
      prettyJson + = "\ n" + indentStr + "]";
    } catch (Exception e) {
      try {
        prettyJson + = "\ n" + prettyPrintJson (jsonObject.get (key) .asJsonObject (), indent + 2);
      } catch (Exception ee) {
        prettyJson + = jsonObject.get (key) .toString ();
      }
    }
    prettyJson + = ",";
  }
prettyJson = prettyJson.substring (0, prettyJson.length () - 1);
  prettyJson + = "\ n" + indentStr + "}";
  return prettyJson;
}
public static String getIndentStr (int indent) {
  String indentStr = "";
  for (int i = 0; i & lt; indent; i ++) {
    indentStr + = "";
  }
  return indentStr;
}

Output:

{
 "firstName": "Json",
 "lastName": "Smith",
 "age": 30,
 "address":
 {
  "streetAddress": "666 1nd Street",
  "city": "New York",
  "state": "NY",
  "postalCode": 10021
 },
 "phoneNumbers":
 [
  {
   "type": "home",
   "number": "542 666-1234"
  },
  {
   "type": "fax",
   "number": "653 666-4567"
  }
 ],
 "friends":
 [
  {
   "firstName": "Test",
   "lastName": "Snow",
   "age": 20,
   "phoneNumbers":
   [
    {
     "type": "home",
     "number": "141 111-1234"
    }
   ],
   "friends":
   [
    {
     "firstName": "UnknownFirstName",
     "lastName": "UnknownLastName",
     "age": 999,
     "phoneNumbers":
     [
      {
       "type": "home",
       "number": "000 000-0000"
      }
     ]
    }
   ]
  },
  {
   "firstName": "Flash",
   "lastName": "Tompson",
   "age": 23,
   "phoneNumbers":
   [
    {
     "type": "home",
     "number": "999 111-1234"
    }
   ]
  }
 ]
}

Answer 4, authority 4%

General information about parsers is located here, which can help in choosing and understand what he can do. The text and table below are taken from a post on Habrahabr :
Java programmer’s cheat sheet 8. Libraries for working with Json , author of the article @ VedeninVyacheslav

There are the following serialization and deserialization methods among
the specified libraries (from simplest to most complex):

  1. Data bind
  2. Tree Model
  3. Streaming API
  4. XPath analogs (optional)

Data bind

The most popular and easiest way – you just specify the class,
which needs to be converted to json , maybe mark some of the fields
annotations (and often even this is optional), and the library itself
turns this class and its entire class hierarchy into json .

Pros : The most simple of them all

Cons : speed and memory. Most libraries use reflection and the like. methods for working with Java classes (although not all) that
obviously not very fast. In addition, the entire json file at once
turns into Java objects, which can simply exhaust all
available memory if you try to process a very large json .

Conclusion : if there are no problems with performance, memory and you are not going to handle multi-gigabyte json’y , most likely the most
the best way.


Tree Model

This parser represents json as Java classes such as
Node or `JsonElement with a hierarchical structure, and already itself
the programmer bypasses them and gets information from them.

Pros : usually faster than the first method and easier than the third

Cons : inferior to Data bind in simplicity, plus a number of libraries are able to generate classes for Data bind , and not use
reflection, in this case the fact that Tree Model will not be faster
obviously, besides, the problem of huge files and limitations is not solved
memory.


Streaming API

The lowest-level method, in fact, the programmer manually disassembles
tokens json’a . But there are no limits on memory and in theory
maximum performance.

Pros : performance and minimal memory consumption

Cons : Difficulty to use


XPath analogs

Not very suitable if you need to get all information from json ‘a, but
allows by writing an expression such as $ .store.book [*]. author to get a list of all authors of all books from the json ‘a store. That is, it is easy to receive
part of information from json ‘a.

Pros : allows you to quickly get information from json ‘and by complex criteria

Cons : not very suitable when all information from json ‘is needed, does not work in the opposite direction for forming json ‘ s


A table of libraries and the parsing methods they support:

Method \ Name Fastjson Gson LoganSquare JSONjava Moshi Jackson Genson JsonPath SimpleJson
Data bind Yes Yes Yes - Yes Yes Yes - -
Tree Model - Yes - Yes - Yes - - Yes
Streaming API - Yes - - - Yes - - -
XPath counterparts Yes - - - - - - Yes -
Generating classes - - Yes - - - - -
 for Data bind *
Works with Yes Yes No - Yes Yes Yes -
static inner class **
Mandatory No No Yes - No No No -
 annotations ***

* – Generating classes for Data bind allows you to generate classes at compile time, which in theory should give a significant increase in library performance,

** – Works with static inner class only makes sense for the Data bind case, is it possible to serialize and deserialize for the case of static inner classes (it is not recommended to serialize non-static inner classes),

*** – also only for the case of Data bind, is it possible not to use annotations or their use is highly recommended,

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions