- JSON.simple – Read and Write JSON
- Пример работы с Json Simple в Java: парсинг и создание JSON
- Обзор Json Simple API
- Json Simple API. Пример разбора JSON строки и создания нового JSON объекта
- Создание maven проекта
- json-simple example
- json-simple
- json-simple maven
- json-simple example to write JSON to file
- json-simple example to read JSON from file
- Java Guides
- JSON.simple maven dependency
- 1. Write JSON to File in Java using JSON.simple Library
- 2. Read JSON from a File in Java using JSON-simple Library
- Reference
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
Пример работы с Json Simple в Java: парсинг и создание JSON
Этой статьей я начну серию публикаций по работе с JSON в Java. Для начала пройдусь по знакомым и простым решениям, а затем перейду к продвинутым библиотекам. Примером «простых решений» сегодня будет работа с Json Simple, а именно парсинг (разбор) существующего JSON объекта и создание нового.
Обзор Json Simple API
Json Simple — представляет собой простой API для обработки JSON. Сам API состоит из около 13 классов, основу которых составляют следующие 5 классов:
- Класс JSONParser предназначен для разбора строки с JSON-содержимым. Он принимает объект java.io.Reader или строку.
- Класс JSONObject — это Java представление JSON строки. Класс JSONObject наследует HashMap и хранит пары ключ — значение. Также у него есть очень полезный метод writeJSONString(Map map, Writer out), который используется для конвертации мапы в JSON строку.
- Класс JSONArray представляет собой коллекцию. Он наследует ArrayList и реализует интерфейсы JSONAware и JSONStreamAware .
- JSONValue — класс для парсинга JSON строки в Java объекты. Для этого он использует класс JSONParser. JSONValue содержит множество полезных методов для создания JSON из различных типов, например, метод writeJSONString(Object value, Writer out) создаст JSON-строку из Java объекта. Он также имеет методы для работы со специальными (управляющими) символами используя метод escape(String s). С помощью этого метода можно безопасно работать с кавычками «» и такими символами, как \f, \t, \n, \, /, \r, \b и многими другими.
- Интерфейс JSONAware . Класс должен реализовывать этот интерфейс, чтобы конвертироваться в JSON формат.
Json Simple API. Пример разбора JSON строки и создания нового JSON объекта
Ниже описан пример парсинга строки с JSON содержимым, а именно текущей погоды в каком-то городе. Я использовал сервис Openweathermap.org для получения данных о погоде.
Если Вы хотите просто попробовать JSON Simple API в действии и не хотите заморачиваться над получением этих данных с какого-то сервиса, то просто скопируйте полученный JSON по этой ссылке: openweather и используйте его в виде обычной строки в Java.
Создание maven проекта
Для удобства я создал простой maven проект в Intellij IDEA и добавил в зависимости последнюю версию json-simple в файле pom.xml:
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 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.
com.googlecode.json-simple json-simple 1.1.1
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()); > >
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 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") Iteratorit = cities.iterator(); while (it.hasNext()) < System.out.println("City = " + it.next()); >reader.close(); > >
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
Java Guides
JSON.simple is a simple Java library for JSON processing, read and write JSON data and full compliance with JSON specification (RFC4627).
In this JSON.simple tutorial, we will see quick examples to write JSON file with JSON.simple and then we will read JSON file back.
JSON.simple maven dependency
https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple --> dependency> groupId>com.googlecode.json-simplegroupId> artifactId>json-simpleartifactId> version>1.1.1version> dependency>
In the below examples, we use two important classes of JSON.simple library to read and write a JSON to file in Java.
- 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.
1. Write JSON to File in Java using JSON.simple Library
In this example, we create an array with 3 user objects using JSONObject and JSONArray classes and write to a file «users.json«:
package net.javaguides.jsonsimple; import java.io.FileWriter; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class WriteJSON < @SuppressWarnings("unchecked") public static void main(String[] args) < //First User JSONObject userDetails = new JSONObject(); userDetails.put("id", 100); userDetails.put("firstName", "Ramesh"); userDetails.put("lastName", "Fadatare"); userDetails.put("userName", "Ramesh Fadatare"); userDetails.put("email", "ramesh@gmail.com"); //Second user JSONObject userDetails1 = new JSONObject(); userDetails1.put("id", 101); userDetails1.put("firstName", "John"); userDetails1.put("lastName", "Cena"); userDetails1.put("userName", "John Cena"); userDetails1.put("email", "john@gmail.com"); // Third User JSONObject userDetails2 = new JSONObject(); userDetails2.put("id", 102); userDetails2.put("firstName", "Tony"); userDetails2.put("lastName", "stark"); userDetails2.put("userName", "Tony stark"); userDetails2.put("email", "tony@gmail.com"); //Add employees to list JSONArray userList = new JSONArray(); userList.add(userDetails); userList.add(userDetails1); userList.add(userDetails2); //Write JSON file try (FileWriter file = new FileWriter("users.json")) < file.write(userList.toJSONString()); file.flush(); > catch (IOException e) < e.printStackTrace(); > > >
[ < "firstName": "Ramesh", "lastName": "Fadatare", "id": 100, "userName": "Ramesh Fadatare", "email": "ramesh@gmail.com" >, < "firstName": "John", "lastName": "Cena", "id": 101, "userName": "John Cena", "email": "john@gmail.com" >, < "firstName": "Tony", "lastName": "stark", "id": 102, "userName": "Tony stark", "email": "tony@gmail.com" > ]
2. Read JSON from a File in Java using JSON-simple Library
package net.javaguides.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 ReadJSON < @SuppressWarnings("unchecked") public static void main(String[] args) < // JSON parser object to parse read file JSONParser jsonParser = new JSONParser(); try (FileReader reader = new FileReader("users.json")) < // Read JSON file Object obj = jsonParser.parse(reader); JSONArray userList = (JSONArray) obj; // Iterate over employee array userList.forEach(user - > parseUserObject((JSONObject) user)); > catch (FileNotFoundException e) < e.printStackTrace(); > catch (IOException e) < e.printStackTrace(); > catch (ParseException e) < e.printStackTrace(); > > private static void parseUserObject(JSONObject user) < // Get user first name Long id = (Long) user.get("id"); System.out.println(id); // Get user first name String firstName = (String) user.get("firstName"); System.out.println(firstName); // Get user last name String lastName = (String) user.get("lastName"); System.out.println(lastName); // Get user website name String userName = (String) user.get("userName"); System.out.println(userName); // Get user email name String email = (String) user.get("email"); System.out.println(email); > >
100 Ramesh Fadatare Ramesh Fadatare ramesh@gmail.com 101 John Cena John Cena john@gmail.com 102 Tony stark Tony stark tony@gmail.com