Tutorial

json-simple example

Published on August 3, 2022
Default avatar

By Pankaj

json-simple example

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

json-simple is a simple java toolkit for JSON. json-simple library is fully compliance with JSON specification (RFC4627).

json-simple

json-simple, json simple example, json example 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.

json-simple maven

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>

json-simple example to write JSON to file

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

json-simple example to read JSON from file

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.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
June 22, 2021

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

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 15, 2017

    Bravos

    - Dana

      Try DigitalOcean for free

      Click below to sign up and get $200 of credit to try our products over 60 days!

      Sign up

      Join the Tech Talk
      Success! Thank you! Please check your email for further details.

      Please complete your information!

      Get our biweekly newsletter

      Sign up for Infrastructure as a Newsletter.

      Hollie's Hub for Good

      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

      Become a contributor

      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

      Welcome to the developer cloud

      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

      Learn more
      DigitalOcean Cloud Control Panel