json-simple is a simple java toolkit for JSON. json-simple library is fully compliance with JSON specification (RFC4627).
json-simple uses Map and List internally for JSON processing. We can use json-simple for parsing JSON data as well as writing JSON to file. One of the best feature of json-simple is that it has no dependency on any third party libraries. json-simple is very lightweight API and serves well with simple JSON requirements.
We can add json-simple library to our project by downloading it from here. Since json-simple is available in maven central repository, best way is to add it’s dependency in pom.xml file.
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
Most important class in json-simple API is org.json.simple.JSONObject
. We create instance of JSONObject
and put key-value pairs into it. JSONObject toJSONString
method returns the JSON in String format that we can write to file. For writing list to a JSON key, we can use org.json.simple.JSONArray
.
package com.journaldev.json.write;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JsonSimpleWriter {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("name", "Pankaj Kumar");
obj.put("age", new Integer(32));
JSONArray cities = new JSONArray();
cities.add("New York");
cities.add("Bangalore");
cities.add("San Francisco");
obj.put("cities", cities);
try {
FileWriter file = new FileWriter("data.json");
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(obj.toJSONString());
}
}
Above class will write data.json
, below is the JSON content of this file.
{"cities":["New York","Bangalore","San Francisco"],"name":"Pankaj Kumar","age":32}
Notice the @SuppressWarnings("unchecked")
annotation on main method? This was done to avoid warnings related to Type safety. JSONObject
extends HashMap but doesn’t support Generics, so Eclipse IDE gives warning as below.
Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap<K,V> should be parameterized
For reading JSON from file, we have to use org.json.simple.parser.JSONParser
class. JSONParser parse
method returns JSONObject. Then we can retrieve values by passing key names. Below is json-simple example to read JSON from file.
package com.journaldev.json.write;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonSimpleReader {
public static void main(String[] args) throws ParseException, FileNotFoundException, IOException {
JSONParser parser = new JSONParser();
Reader reader = new FileReader("data.json");
Object jsonObj = parser.parse(reader);
JSONObject jsonObject = (JSONObject) jsonObj;
String name = (String) jsonObject.get("name");
System.out.println("Name = " + name);
long age = (Long) jsonObject.get("age");
System.out.println("Age = " + age);
JSONArray cities = (JSONArray) jsonObject.get("cities");
@SuppressWarnings("unchecked")
Iterator<String> it = cities.iterator();
while (it.hasNext()) {
System.out.println("City = " + it.next());
}
reader.close();
}
}
Above json-simple example produces following output.
Name = Pankaj Kumar
Age = 32
City = New York
City = Bangalore
City = San Francisco
That’s all for a quick roundup of json-simple. However if you want to work with complex JSON data, you should use Jackson or Gson. You can also give JSR353 a try that got added into Java 7.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev
Gives an error at System.out.println(“City = ” + it.next()); Exception in thread “main” java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to java.lang.String
- Radee
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.