Java JSON Tutorial and Example: JSON-Java (org.json)

Example of how to parse JSON using JSON-Java (org.json) library in Java or Android application.

1 Installation

The JSON-Java (JSON in Java) library is also known as org.json.

org.json implementation has already been included in Android SDK. So you can use it without any extra installation in Android projects.

You have two optional ways to install org.json in a Java project.

  • Simplely download the org.json jar file, then paste it to your project folder and add it to your project build path.
  • If your project is a Maven project, just add a dependency to the Maven pom.xml file of your project.

    <!-- pom.xml -->
    
    <dependencies>
        <!-- ... -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>
        <!-- ... -->
    </dependencies>

2 Create JSON using org.json

2.1 Create JSON straightforwardly

org.json uses its JSONObject (Java Doc) class to create or parse JSON. JSONObject APIs work much like the Java Map APIs and are simple to use.

import org.json.JSONObject;

private static void createJSON(boolean prettyPrint) {    
    JSONObject tomJsonObj = new JSONObject();
    tomJsonObj.put("name", "Tom");
    tomJsonObj.put("birthday", "1940-02-10");
    tomJsonObj.put("age", 76);
    tomJsonObj.put("married", false);
    
    // Cannot set null directly
    tomJsonObj.put("car", JSONObject.NULL);
    
    tomJsonObj.put("favorite_foods", new String[] { "cookie", "fish", "chips" });
    
    // {"id": 100001, "nationality", "American"}
    JSONObject passportJsonObj = new JSONObject();
    passportJsonObj.put("id", 100001);
    passportJsonObj.put("nationality", "American");
    // Value of a key is a JSONObject
    tomJsonObj.put("passport", passportJsonObj);
    
    if (prettyPrint) {
        // With four indent spaces
        System.out.println(tomJsonObj.toString(4));
    } else {
        System.out.println(tomJsonObj.toString());
    }
}

The output JSON string is listed as follows.

{
    "car": null,
    "birthday": "1940-02-10",
    "married": false,
    "age": 76,
    "name": "Tom",
    "favorite_foods": [
        "cookie",
        "fish",
        "chips"
    ],
    "passport": {
        "id": "100001",
        "nationality": "American"
    }
}

Tips: how to set value of a key to null in org.json.JSONObject?

You must set the value to JSONObject.NULL instead of Java's own null.

Tips: how to tell JSONObject to output pretty-print JSON string?

An overloading toString() method of JSONObject can accept an integer argument which means the number of spaces to indent.

tomJsonObj.toString(4);

2.2 Create JSON from Java Map object

JSONObject provided a constructor to convert key-value pairs data to JSON object from Java Map object.

import org.json.JSONObject;

private static void createJSONFromMap(boolean prettyPrint) {
    // Java Map object to store key-value pairs
    Map<String, Object> tom = new HashMap<String, Object>();
    tom.put("name", "Tom");
    tom.put("birthday", "1940-02-10");
    tom.put("age", 76);
    tom.put("married", false);
    
    // Must be  JSONObject.NULL instead of null
    tom.put("car", JSONObject.NULL);
    tom.put("favorite_foods", new String[] { "cookie", "fish", "chips" });

    Map<String, Object> passport = new HashMap<String, Object>();
    passport.put("id", 100001);
    passport.put("nationality", "American");
    tom.put("passport", passport);
    
    // Create JSON object from Java Map
    JSONObject tomJsonObj = new JSONObject(tom);
    
    if (prettyPrint) {
        // With 4 indent spaces
        System.out.println(tomJsonObj.toString(4));
    } else {
        System.out.println(tomJsonObj.toString());
    }
}

2.3 Create JSON from JavaBean

The recommended way is to create JSON object from JavaBean instance.

Here are two sample JavaBean classes we will used later, PetBean and PassportBean.

The PassportBean.java source file:

package com.codevoila.javatuts.jsondemo;

public class PassportBean {
    private int id;
    private String nationality;
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getNationality() {
        return nationality;
    }
    
    public void setNationality(String nationality) {
        this.nationality = nationality;
    }
    
    @Override
    public String toString() {
        return "[" + this.nationality + "-"  + this.id +"]";
    }
}

And the PetBean.java source file:

package com.codevoila.javatuts.jsondemo;

import java.util.Date;
import java.util.Set;

public class PetBean {
    private String name;
    private Date birthday;
    private int age;
    private boolean married;
    private Object car;
    private Set<String> favorite_foods;
    private PassportBean passport;
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public Date getBirthday() {
        return birthday;
    }
    
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    public boolean isMarried() {
        return married;
    }
    
    public void setMarried(boolean married) {
        this.married = married;
    }
    
    public Object getCar() {
        return car;
    }
    
    public void setCar(Object car) {
        this.car = car;
    }
    
    public Set<String> getFavorite_foods() {
        return favorite_foods;
    }
    
    public void setFavorite_foods(Set<String> favorite_foods) {
        this.favorite_foods = favorite_foods;
    }
    
    public PassportBean getPassport() {
        return passport;
    }
    
    public void setPassport(PassportBean passport) {
        this.passport = passport;
    }
}

Please pay attention to the data type of some properties:

  • favorite_foods is Java collection;
  • passport property is another JavaBean class;
  • birthday property is java.util.Date.

It's convenient to convert JavaBean object instance to JSON object using another overloading constructor method of JSONObject class.

private static void createJSONFromBean(boolean prettyPrint) throws Exception {    
    PetBean tom = new PetBean();
    tom.setName("Tom");
    
    DateFormat df = new SimpleDateFormat("yy-MM-dd");
    Date date = df.parse("1940-02-10");
    tom.setBirthday(date);
    
    tom.setAge(76);
    tom.setMarried(false);
    
    tom.setCar(JSONObject.NULL);
    
    tom.setFavorite_foods(new HashSet<String>(Arrays.asList(new String[] { "cookie", "fish", "chips" })));
    
    PassportBean passport = new PassportBean();
    passport.setId(100001);
    passport.setNationality("American");
    
    tom.setPassport(passport);
    
    // Create JSON object from JavaBean
    JSONObject tomJsonObj = new JSONObject(tom);
    
    if (prettyPrint) {
        // With 4 indent spaces
        System.out.println(tomJsonObj.toString(4));
    } else {
        System.out.println(tomJsonObj.toString());
    }
}

3 Parse JSON using org.json

First of all, I'd like to give a sample JSON file parsed later, which is named tom.json.

{
  "name": "Tom",
  "birthday": "1940-02-10",
  "age": 76,
  "married": false,
  "car": null,
  "favorite_foods": [
    "cookie",
    "chips",
    "fish"
  ],
  "passport": {
    "id": 100001,
    "nationality": "American"
  }
}

Read the JSON file and parse its content into JSONObject instance.

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.json.JSONObject;

private static void readJSON() throws Exception {
    File file = new File("./tom.json");
    String content = FileUtils.readFileToString(file, "utf-8");
    
    // Convert JSON string to JSONObject
    JSONObject tomJsonObject = new JSONObject(content);    
}

Note that I used Apache commons-io library to load JSON file. You can download the commons-io jar yourself or add a Maven dependency to your project.

Then we can retrieve key-value pairs of the JSON data using the getXXX and optXXX APIs provided by org.json.JSONObject class.

Retrieve the name:

String name = tomJsonObject.getString("name");

Access the age:

int age = tomJsonObject.getInt("age");

Obtain the array of favorite_foods:

JSONArray favorite_foods = tomJsonObject.getJSONArray("favorite_foods");

for (int i = 0; i < favorite_foods.length(); i++) {
    String food = (String) favorite_foods.get(i);
    System.out.println(food);
}

// Or convert the JSONArray to Java List
List<Object> foods = favorite_foods.toList();
for (Object food : foods) {
    System.out.println((String)food);
}

Get a boolean value:

boolean married = tomJsonObject.getBoolean("married");

The scenario that a JSONObject instance as the value of a key:

JSONObject passportJsonObject = tomJsonObject.getJSONObject("passport");
String nationality = passportJsonObject.getString("nationality");

Tips: how to handle the nonexistent key or the null (JSONObject.NULL) value in JSONObject?

For example in above sample JSON file, the key car exists but the vaule is null (JSONObject.NULL); the key house doesn't exist at all.

If your requirement is just to check the existence of the specified key, the has(String key) method will be your choice.

tomJsonObject.has("car"); // true, "car" key exists even the value is JSONObject.NULL
tomJsonObject.has("house"); // false, the "house" key doesn't exist

As mentioned above, the null in JSON is totally different with Java's own null in JSONObject's view. JSONObject uses a constant named JSONObject.NULL to represent the null in JSON. So sometimes you may need to check these two scenarios respectively.

/* Key exists but value is null (JSONObject.NULL) */
tomJsonObject.opt("car") == JSONObject.NULL; // true
tomJsonObject.opt("car") == null;   // false, JSONObject.NULL is not the same as Java's own null

/* The key doesn't exist at all */
tomJsonObject.opt("house") == JSONObject.NULL;  // false
tomJsonObject.opt("house") == null;     // true

On the contrary, the isNull(String key) method will not differentiate the two scenarios.

tomJsonObject.isNull("car");    // true
tomJsonObject.isNull("house");  // true

if (tomJsonObject.isNull("car")) {
    System.out.println("No car ~");
}
    
if (tomJsonObject.isNull("house")) {
    System.out.println("No house ~");
}

Additionally, you can specify a default return value if a key doesn't exist or its value is JSONObject.NULL.

String car = tomJsonObject.optString("car", "No car!");
System.out.println(car);    // "No car!"


String house = tomJsonObject.optString("house", "No house!");
System.out.println(house);  // "No house!"

4 Summary

Pros:

  • APIs of org.json are straightforward and easy to use.
  • Already included in Android SDK.

Cons:

org.json can't convert JSON to Java object directly.

Comments