Java json-simple

From wikinotes

Documentation

official docs https://code.google.com/archive/p/json-simple/wikis

Dependency Manager

maven

<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

Usage

encode (json object)

import org.json.simple.JSONObject;


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.println(obj);

encode (native objects)

import java.util.LinkedHashMap; 
import java.util.Map; 
import org.json.simple.JSONValue;

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

String jsonText = JSONValue.toJSONString(obj);
System.out.print(jsonText);

merge/update json objects


import org.json.simple.JSONObject;


JSONObject objA = new JSONObject();
objA.put("name", "a");

JSONObject objB = new JSONObject();
objB.put("age", 30);

// update map from A with items from B
objA.putAll(objB);

System.out.println(objA);

decode


import org.json.simple.parser.JSONParser;
import org.json.simple.parser.JSONMap;  // see also JSONArray

JSONParser parser = new JSONParser();

String json_text = "{\"a\": null}";
JSONMap data = parser.parse(json_text);

System.out.println(data.get("a"));