Java Programming
JSON Parsing
Coding Tutorial
Java JSON API
Programming Skills

How to parse JSON in Java

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Parsing JSON (JavaScript Object Notation) in Java is a fundamental skill for many developers, especially those who work with web services, APIs, or configurations. JSON is a lightweight data interchange format that is easy to read and write for humans, and easy to parse and generate for machines. In Java, parsing JSON typically involves using libraries as Java does not have built-in support for JSON like JavaScript. The most commonly used libraries are Jackson, Gson, and JSONP. This article will guide you through using these libraries to parse JSON in Java.

Understanding JSON Structure

JSON is built on two structures:

  1. A collection of key/value pairs: In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  2. An ordered list of values: Generally realized as an array, vector, list, or sequence.

Example JSON:

json
1{
2  "name": "John Doe",
3  "age": 30,
4  "isEmployed": true,
5  "address": {
6    "street": "123 Elm St",
7    "city": "Somewhere"
8  },
9  "phoneNumbers": [
10    {"type": "home", "number": "212 555-1234"},
11    {"type": "fax", "number": "646 555-4567"}
12  ]
13}

Using Gson to Parse JSON

Gson is a Java library that can be used to convert Java Objects into their JSON representation and vice versa. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Basic Usage: To parse JSON using Gson, you would do the following:

java
1import com.google.gson.Gson;
2
3public class Main {
4    public static void main(String[] args) {
5        String json = "{\"name\": \"John Doe\", \"age\": 30}";
6        Gson gson = new Gson();
7        Person person = gson.fromJson(json, Person.class);
8        System.out.println(person.name); // John Doe
9    }
10}
11
12class Person {
13    String name;
14    int age;
15}

Using Jackson to Parse JSON

Jackson is a high-performance JSON processor for Java. Unlike Gson, Jackson can read JSON as a tree (like DOM for XML), or it can also work with JSON in a streaming manner. This makes it very versatile and powerful.

Basic Usage: To parse JSON using Jackson:

java
1import com.fasterxml.jackson.databind.ObjectMapper;
2
3public class Main {
4    public static void main(String[] args) throws IOException {
5        String json = "{\"name\": \"John Doe\", \"age\": 30}";
6        ObjectMapper mapper = new ObjectMapper();
7        Person person = mapper.readValue(json, Person.class);
8        System.out.println(person.name); // John Doe
9    }
10
11    static class Person {
12        public String name;
13        public int age;
14    }
15}

Using JSONP (JSON Processing)

JSONP (JSON Processing) is part of Java EE and provides a standard API to parse JSON, including object models and streaming. It's not as popular as Gson or Jackson but is a part of the standard Java EE API.

Basic Usage: To parse JSON using JSONP:

java
1import javax.json.Json;
2import javax.json.JsonObject;
3import javax.json.JsonReader;
4import java.io.StringReader;
5
6public class Main {
7    public static void main(String[] args) {
8        String json = "{\"name\": \"John Doe\", \"age\": 30}";
9        JsonReader reader = Json.createReader(new StringReader(json));
10        JsonObject jsonObject = reader.readObject();
11        reader.close();
12        System.out.println(jsonObject.getString("name")); // John Doe
13    }
14}

Comparing JSON Parsing Libraries

FeatureGsonJacksonJSONP
OriginGoogleFasterXMLJava EE API
PerformanceGoodVery GoodGood
Ease of UseVery EasyModerateModerate
PopularityVery HighVery HighLow
API TypeReflectionStreaming and ReflectionModel and Streaming

Conclusion

While all three libraries can be used to parse JSON in Java, the choice often depends on specific needs such as performance requirements, ease of use, and the specific Java environment. Gson and Jackson are more popular in the Java community with robust support and frequent updates while JSONP provides a standard method that fits in naturally with Java EE environments. By understanding how to use these libraries, developers can effectively handle JSON data within Java applications.


Course illustration
Course illustration

All Rights Reserved.