json-simple example

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.

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.

Above class will write data.json, below is the JSON content of this file.

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.

Above json-simple example produces following output.

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.

By admin

Leave a Reply