How to read and write JSON with json-simple
Json-simple is a simple java library used to encode and decode JSON. It is full compliance with JSON specification (RFC4627) and is widely used in big projects, see the website for details.
Step1 — Dependency
If you are using a maven structure for your project you can added as dependency:
com.googlecode.json-simple json-simple 1.1.1
otherwise download the jar file and attached it to the project.
Step2 — Generate the JSON object
To generate an object use JSONObject and add the content similar to Map/Hashmap.
/* Create simple object */ JSONObject object = new JSONObject(); object.put("id", new Integer(1001)); object.put("name", "John Doe");
or if you need an array you can use JSONArray :
/* json array added manually */ JSONArray array = new JSONArray(); array.add("product 1"); array.add("product 2"); /* json array added from an ArrayList object */ ArrayList list = new ArrayList(); list.add("list element 1"); list.add("list element 2"); list.add("list element 3"); array.addAll(list);
Also can be created complex JSON structures by adding an JSONObject on other JSONObject .
/* add the list to initial object */ object.put("list", array);
Step3 — Write the JSON object to file
To write the json to a file will use FileWriter from java.io package.
/* write the complex object to a file */ try < FileWriter file = new FileWriter("test.json"); file.write(object.toString()); file.flush(); file.close(); >catch (IOException e)
Note: the path for the file is the folder root of the project.
Step4 — Read the JSON from file
To recreate the JSONObject json-simple library provides a class to parse the input, JSONParser and this can use multiple sources.
JSONParser parser = new JSONParser(); /* Get the file content into the JSONObject */ Object obj = parser.parse(new FileReader("test.json")); JSONObject jsonObject = (JSONObject)obj;
From this point you have access to all object within jsonObject.
Example
Here is the print for the entire example:
package com.admfactory.json; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; public class JsonSimpleTests < /** * How to create an JSON object and write it to a file */ public static void createJSONObject() < System.out.println("Write an JSON Object"); /* Create simple object */ JSONObject object = new JSONObject(); object.put("id", new Integer(1001)); object.put("name", "John Doe"); System.out.println("Simple object: " + object); /* json array added manualy */ JSONArray array = new JSONArray(); array.add("product 1"); array.add("product 2"); /* json array added from an ArrayList object */ ArrayListlist = new ArrayList(); list.add("list element 1"); list.add("list element 2"); list.add("list element 3"); array.addAll(list); System.out.println("Array object: " + array); /* add the list to initial object */ object.put("list", array); System.out.println("Complex object:" + object); /* write the complex object to a file */ try < FileWriter file = new FileWriter("test.json"); file.write(object.toString()); file.flush(); file.close(); >catch (IOException e) < e.printStackTrace(); >> /** * How to read an json object from a file and display it on the console * */ public static void readJSONObject() < JSONParser parser = new JSONParser(); try < /* Get the file content into the JSONObject */ Object obj = parser.parse(new FileReader("test.json")); JSONObject jsonObject = (JSONObject)obj; System.out.println("Object from file:" + jsonObject); /* Read simple value */ Long Read a list */ ArrayListlist = (ArrayList)jsonObject.get("list"); for (int i = 0; i < list.size(); i++) < System.out.println(i+ ": " + list.get(i)); >> catch (Exception e) < e.printStackTrace(); >> public static void main(String[] args) < System.out.println("json-simple examples"); System.out.println(); createJSONObject(); System.out.println(); readJSONObject(); >>
Output
The console output from our test program. Check also the content of the test.json file located in root folder of your project.
json-simple examples Write an JSON Object Simple object: Array object: ["product 1","product 2","list element 1","list element 2","list element 3"] Complex object: Object from file: id:1001 0: product 1 1: product 2 2: list element 1 3: list element 2 4: list element 3
References
JSON.simple – Read and Write JSON
JSON.simple is a lightweight JSON processing library that can be used to read and write JSON files and strings. The encoded/decoded JSON will be in full compliance with JSON specification (RFC4627).
JSON.simple library is pretty old and has not been updated since march, 2012. Google GSON library is a good option for reading and writing JSON.
In this Java JSON tutorial, we will first see a quick example of writing to a JSON file and then we will read JSON from the file.
- Full compliance with JSON specification (RFC4627).
- Supports encode, decode/parse and escape JSON.
- Easy to use by reusing Map and List interfaces.
- Supports streaming output of JSON text.
- High performance.
- No dependency on external libraries.
Update pom.xml with json-simple maven dependency.
com.googlecode.json-simple json-simple 1.1.1
To write JSON test into the file, we will be working with mainly two classes:
- JSONArray : To write data in json arrays. Use its add() method to add objects of type JSONObject .
- JSONObject : To write json objects. Use it’s put() method to populate fields.
After populating the above objects, use FileWriter instance to write the JSON file.
package com.howtodoinjava.demo.jsonsimple; import java.io.FileWriter; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class WriteJSONExample < @SuppressWarnings("unchecked") public static void main( String[] args ) < //First Employee JSONObject employeeDetails = new JSONObject(); employeeDetails.put("firstName", "Lokesh"); employeeDetails.put("lastName", "Gupta"); employeeDetails.put("website", "howtodoinjava.com"); JSONObject employeeObject = new JSONObject(); employeeObject.put("employee", employeeDetails); //Second Employee JSONObject employeeDetails2 = new JSONObject(); employeeDetails2.put("firstName", "Brian"); employeeDetails2.put("lastName", "Schultz"); employeeDetails2.put("website", "example.com"); JSONObject employeeObject2 = new JSONObject(); employeeObject2.put("employee", employeeDetails2); //Add employees to list JSONArray employeeList = new JSONArray(); employeeList.add(employeeObject); employeeList.add(employeeObject2); //Write JSON file try (FileWriter file = new FileWriter("employees.json")) < //We can write any JSONArray or JSONObject instance to the file file.write(employeeList.toJSONString()); file.flush(); >catch (IOException e) < e.printStackTrace(); >> >
To read JSON from file, we will use the JSON file we created in the previous example.
- First of all, we will create JSONParser instance to parse JSON file.
- Use FileReader to read JSON file and pass it to parser.
- Start reading the JSON objects one by one, based on their type i.e. JSONArray and JSONObject .
package com.howtodoinjava.demo.jsonsimple; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class ReadJSONExample < @SuppressWarnings("unchecked") public static void main(String[] args) < //JSON parser object to parse read file JSONParser jsonParser = new JSONParser(); try (FileReader reader = new FileReader("employees.json")) < //Read JSON file Object obj = jsonParser.parse(reader); JSONArray employeeList = (JSONArray) obj; System.out.println(employeeList); //Iterate over employee array employeeList.forEach( emp ->parseEmployeeObject( (JSONObject) emp ) ); > catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >catch (ParseException e) < e.printStackTrace(); >> private static void parseEmployeeObject(JSONObject employee) < //Get employee object within list JSONObject employeeObject = (JSONObject) employee.get("employee"); //Get employee first name String firstName = (String) employeeObject.get("firstName"); System.out.println(firstName); //Get employee last name String lastName = (String) employeeObject.get("lastName"); System.out.println(lastName); //Get employee website name String website = (String) employeeObject.get("website"); System.out.println(website); >>
[ >, > ] Lokesh Gupta howtodoinjava.com Brian Schultz example.com
How to read and write JSON using JSON.simple in Java
In an earlier article, I wrote about reading and writing JSON files in Java using different open-source libraries. In this article, I will focus on one of those libraries — JSON.simple — to convert Java Objects into JSON and back.
JSON.simple is a lightweight Java library for processing JSON that can be used to read, write, and parse JSON. The produced JSON is fully complaint with JSON specification (RFC4627).
implementation 'com.github.cliftonlabs:json-simple:3.1.0'
dependency> groupId>com.github.cliftonlabsgroupId> artifactId>json-simpleartifactId> version>3.1.0version> dependency>
Let us create a simple Java class named Book that we will use to convert Java Objects to JSON and back. JSON.simple requires this class to implement the Jsonable interface as well as override the toJson() method: Book.java
package com.attacomsian; import com.github.cliftonlabs.json_simple.JsonObject; import com.github.cliftonlabs.json_simple.Jsonable; import java.io.IOException; import java.io.Writer; public class Book implements Jsonable private String title; private String isbn; private long year; private String[] authors; public Book() > public Book(String title, String isbn, long year, String[] authors) this.title = title; this.isbn = isbn; this.year = year; this.authors = authors; > // getters and setters, equals(), toString() . (omitted for brevity) @Override public String toJson() JsonObject json = new JsonObject(); json.put("title", this.title); json.put("isbn", this.isbn); json.put("year", this.year); json.put("authors", this.authors); return json.toJson(); > @Override public void toJson(Writer writable) throws IOException try writable.write(this.toJson()); > catch (Exception ignored) > > >
JSON.simple provides the Jsoner utility class for converting a Java object to a JSON string, as shown below:
try // create book object Book book = new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">); // convert book object to JSON String json = Jsoner.serialize(book); // prettify JSON json = Jsoner.prettyPrint(json); // print JSON System.out.println(json); > catch (Exception ex) ex.printStackTrace(); >
"year":1998, "isbn":"978-0131872486", "title":"Thinking in Java", "authors":[ "Bruce Eckel" ] >
You can even write the converted JSON string directly to a file using Jsoner.serialize() :
try // create a writer BufferedWriter writer = Files.newBufferedWriter(Paths.get("book.json")); // create book object Book book = new Book("Thinking in Java", "978-0131872486", 1998, new String[] "Bruce Eckel">); // convert book object to JSON and write to book.json Jsoner.serialize(book, writer); // close the writer writer.close(); > catch (Exception ex) ex.printStackTrace(); >
"year":1998,"isbn":"978-0131872486","title":"Thinking in Java","authors":["Bruce Eckel"]>
To convert a list of Java objects to a JSON array, all you need to do is just create a List of Book and pass it to Jsoner.serialize() , as shown below:
try // create a writer BufferedWriter writer = Files.newBufferedWriter(Paths.get("books.json")); // create books list ListBook> books = Arrays.asList( new Book("Thinking in Java", "978-0131872486", 1998, new String[]"Bruce Eckel">), new Book("Head First Java", "0596009208", 2003, new String[]"Kathy Sierra", "Bert Bates">) ); // convert books list to JSON and write to books.json Jsoner.serialize(books, writer); // close the writer writer.close(); > catch (Exception ex) ex.printStackTrace(); >
[ "year": 1998, "isbn": "978-0131872486", "title": "Thinking in Java", "authors": [ "Bruce Eckel" ] >, "year": 2003, "isbn": "0596009208", "title": "Head First Java", "authors": [ "Kathy Sierra", "Bert Bates" ] > ]
Unfortunately, there is no direct way to convert a JSON string to a Java Object using JSON.simple. For this, we have to either use the 3rd-party library like Dozer or manually build the object. Let us use the Dozer library by adding the following dependency to your Gradle’s project build.gradle file:
implementation 'com.github.dozermapper:dozer-core:6.5.0'
dependency> groupId>com.github.dozermappergroupId> artifactId>dozer-coreartifactId> version>6.5.0version> dependency>
try // create a reader Reader reader = Files.newBufferedReader(Paths.get("book.json")); // read JSON from a file JsonObject jsonObject = (JsonObject) Jsoner.deserialize(reader); // create a Dozer mapper Mapper mapper = DozerBeanMapperBuilder.buildDefault(); // convert JsonObject to Book Book book = mapper.map(jsonObject, Book.class); // print the book System.out.println(book); // close the reader reader.close(); > catch (Exception ex) ex.printStackTrace(); >
Booktitle='Thinking in Java', isbn='978-0131872486', year=1998, authors=[Bruce Eckel]>
To convert a JSON array to a list of Java Objects, we can use the above example code with a few modifications:
try // create a reader Reader reader = Files.newBufferedReader(Paths.get("books.json")); // read JSON from a file JsonArray objects = Jsoner.deserializeMany(reader); // create a Dozer mapper Mapper mapper = DozerBeanMapperBuilder.buildDefault(); // convert JsonArray to List JsonArray jsonArray = (JsonArray) objects.get(0); ListBook> books = jsonArray.stream() .map(obj -> mapper.map(obj, Book.class)) .collect(Collectors.toList()); // print all books books.forEach(System.out::println); // close the reader reader.close(); > catch (Exception ex) ex.printStackTrace(); >
Booktitle='Thinking in Java', isbn='978-0131872486', year=1998, authors=[Bruce Eckel]> Booktitle='Head First Java', isbn='0596009208', year=2003, authors=[Kathy Sierra, Bert Bates]>
That’s all folks. In this article, you have learned how to read and write JSON using the JSON.simple library in Java. JSON.simple is no longer actively maintained and is only good for simple use cases. For better JSON serialization/deserialization, you should either use Jackson or Gson. Check out the reading and writing JSON files in Java to learn more about all modern JSON libraries. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.