How to work with JSON easily in Java

How to work with JSON easily in Java

JSON is a light-weight, language independent, data interchange format that is being used nowadays on every single web API available out there. If you are willing to manipulate this kind of data in a Java environment, we'll explain you how to achieve it easily using the org.json package.

1. Include org.json package

Java by default doesn't offer any integrated functionality to parse or create JSON unlike PHP or other languages, instead you will need to rely on a third party library/package. In this tutorial, we'll use the org.json. The files in this package implement JSON encoders/decoders in Java. It also includes the capability to convert between JSON and XML, HTTP headers, Cookies, and CDL. This is a reference implementation. There is a large number of JSON packages in Java. Perhaps someday the Java community will standardize on one. Until then, we recommend you to use the org.json package that makes the things pretty easy.

You can either download the jar file of the package from the maven repository and include it manually in your project or if your project is maven based, you may edit the pom.xml file and add the dependency:

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
</dependency>

For more information about this package, please visit the official repository at Maven here. After including the library, you will be able to import the package with import org.json.*; in your code.

2. Using the library to manipulate JSON

As every tutorial in Our Code World, you will learn by doing and reading some examples. We'll share with you a couple of the most used features when you work with JSON in Java:

A. Creating JSON objects

The put method of a JSONObject class allows you to define a new key with a value to the object:

package sandbox;

import org.json.*;

public class Sandbox {
    
    /**
     * Generating a JSON Object
     * 
     * @param args 
     */
    public static void main(String[] args) {
        JSONObject myObject = new JSONObject();

        // Basic strings
        myObject.put("name", "Carlos");
        myObject.put("last_name", "Carlos");
        
        // Primitive values
        myObject.put("age", new Integer(21));
        myObject.put("bank_account_balance", new Double(20.2));
        myObject.put("is_developer", new Boolean(true));
        
        // Key with array
        double[] myList = {1.9, 2.9, 3.4, 3.5};
        myObject.put("number_list", myList);
        
        // Object inside object
        JSONObject subdata = new JSONObject();
        myObject.put("extra_data", subdata);

        // Generate JSON String
        System.out.print(myObject);
    }
}

The code will print the following structure in the console of the generated JSON string:

{
  "number_list": [
    1.9,
    2.9,
    3.4,
    3.5
  ],
  "extra_data": {},
  "name": "Carlos",
  "last_name": "Carlos",
  "bank_account_balance": 20.2,
  "age": 21,
  "is_developer": true
}

B. Creating JSON Arrays

The put method of a JSONArray class allows you to push some value to the array:

package sandbox;

import org.json.*;

public class Sandbox {
    
    /**
     * Generating a JSON Array
     * 
     * @param args 
     */
    public static void main(String[] args) {
        JSONArray myArray = new JSONArray();
        
        // Push mixed values to the array
        myArray.put(1);
        myArray.put(2);
        myArray.put(3);
        myArray.put(4);
        myArray.put(new Boolean(true));
        myArray.put(new Boolean(false));
        myArray.put("Some String Value");
        
        // Generate JSON String
        System.out.print(myArray);
    }
}

The code will print the following structure in the console of the generated JSON string:

[1,2,3,4,true,false,"Some String Value"]

C. Parsing JSON strings

If you are willing to convert a JSON string in your code (converting it to arrays or objects), just provide the string as first argument of the constructor of the class according to the type, for example, if you want to convert a string of JSONArray:

package sandbox;

import org.json.*;

public class Sandbox {
    
    /**
     * Parsing a JSONArray string
     * 
     * @param args 
     */
    public static void main(String[] args) {
        JSONArray myJson = new JSONArray("[123,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]");
        
        // Print first value of the array
        System.out.print(myJson.get(0));
        
        // Print second value of the array
        System.out.print(myJson.get(1));
    }
}

Or if you want to convert a string to a JSONObject:

package sandbox;

import org.json.*;

public class Sandbox {
    
    /**
     * Parsing a JSONObject string
     * 
     * @param args 
     */
    public static void main(String[] args) {
        JSONObject myJson = new JSONObject("{ \"number_list\": [ 1.9, 2.9, 3.4, 3.5 ], \"extra_data\": {}, \"name\": \"Carlos\", \"last_name\": \"Carlos\", \"bank_account_balance\": 20.2, \"age\": 21, \"is_developer\": true }");
        
        // Get some keys from the JSON Object
        System.out.print(myJson.get("name")); // Carlos
        System.out.print(myJson.get("age")); // 21
    }
}

Happy coding !

This could interest you
Become a more social person