Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Use JSON in Java


May 08, 2021 JSON


Table of contents


Use JSON in Java

This tutorial will teach us how to encode and decode JSON using the Java programming language. Let's first prepare the environment for Java programming for JSON.

Environment

Before we can use Java to encode and decode JSON, we need to install an available JSON module. For this tutorial, download and install JSON.simple, and then add the path to the jsonsimple-1.1.1.jar file to the environment variable CLASSPATH.

JSON and Java entity mapping

JSON.simple entity maps are decoded or resolved from left to right, and entity maps are encoded from right to left.

Json Java
string java.lang.String
number java.lang.Number
true | false java.lang.Boolean
Null Null
array java.util.List
object java.util.Map

When decoding, the default specific class for java.util.List is org.json.simple.JSONArray, and the default specific class for java.util.Map is org.simple.JSONObject.

Code JSON in Java

The following simple example shows a JSON object encoded using JSONObject, a sub-class of java.util.HashMap. T here is no order provided here. If you need a strict element order, use an ordered mapping implementation of the JSONValue.to JSONString (map) method, such as java.util.LinkedHashMap.

import org.json.simple.JSONObject;

class JsonEncodeDemo 
{
    public static void main(String[] args)
    {
        JSONObject obj = new JSONObject();

        obj.put("name", "foo");
        obj.put("num", new Integer(100));
        obj.put("balance", new Double(1000.21));
        obj.put("is_vip", new Boolean(true));

        System.out.print(obj);
    }
}

When you compile and execute the above program, you produce results such as the following:

{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}

Here's another example that shows the JSON object flow using Java JSONObject:

java
import org.json.simple.JSONObject;
class JsonEncodeDemo
{
    public static void main(String[] args)
    {
        JSONObject obj = new JSONObject();

        obj.put("name","foo");
        obj.put("num",new Integer(100));
        obj.put("balance",new Double(1000.21));
        obj.put("is_vip",new Boolean(true));

        StringWriter out = new StringWriter();
        obj.writeJSONString(out);
        String jsonText = out.toString();
        System.out.print(jsonText);
    }
}

When you compile and execute the above program, you produce results such as the following:

{"balance": 1000.21, "num":100, "is_vip":true, "name":"foo"}

Decode JSON in Java

The following examples use JSONObject and JSONArray, where JSONObject is java.util.Map and JSONArray is java.util.List, so we can access them using standard operations such as Map or List.

import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;

class JsonDecodeDemo
{
    public static void main(String[] args)
    {
        JSONParser parser=new JSONParser();
        String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
            try{
            Object obj = parser.parse(s);
            JSONArray array = (JSONArray)obj;
            System.out.println("The 2nd element of array");
            System.out.println(array.get(1));
            System.out.println();
            JSONObject obj2 = (JSONObject)array.get(1);
            System.out.println("Field \"1\"");
            System.out.println(obj2.get("1"));

            s = "{}";
            obj = parser.parse(s);
            System.out.println(obj);

            s= "[5,]";
            obj = parser.parse(s);
            System.out.println(obj);

            s= "[5,,2]";
            obj = parser.parse(s);
            System.out.println(obj);
        }catch(ParseException pe){
            System.out.println("position: " + pe.getPosition());
            System.out.println(pe);
        }
    }
}

When you compile and execute the above program, you produce results such as the following:

The 2nd element of array
{"1":{"2":{"3":{"4":[5,{"6":7}]}}}}

Field "1"
{"2":{"3":{"4":[5,{"6":7}]}}}
{}
[5]
[5,2]