Store JSON data in Java

Tags: , , ,



I want to learn JSON data storage in Java using Eclipse, so I googled a lot.

I found JSON.simple and GSON. Are those a good choice?

I went to Properties >> Java Build Path >> Add External JARs. I added json-simple-1.1.1.jar and google-gson-2.2.4-release.zip. Is it right? Where is the JavaDoc located?

Main problem concerns an example found here: JSON.simple example – Read and write JSON, which teaches about JSON.simple. I wrote the following code:

JSONObject object = new JSONObject();
JSONArray array = new JSONArray();
array.add("Bob");
array.add("John");
object.put("nicknames", array);
object.put("from", "US");
object.put("age", 35);
try {
    String path = "";
    FileWriter file = new FileWriter(path);
    String json = object.toJSONString();
    file.write(json);
    file.close();
} catch (IOException io) {
    // Fail
}

But I get the following warnings. What do these mean?

Type safety: The method add(Object) belongs to the raw type ArrayList. References to generic type ArrayList should be parameterized on ‘JSONArray.add’

Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap<K,V> should be parameterized on ‘JSONObject.put’

On a side note, how can I prettify my JSON?

Answer

I found JSON.simple and GSON. Are those a good choice?

At the moment, I like the former very much, but the latter has more features, is more widely used, and is always up-to-date.

Where is the JavaDoc located?

For JSON.simple, see this answer on the site. For GSON, follow this link.

I get some warnings. What do they mean?

Those classes are declared without type parameters for their superclass:

public class JSONObject extends HashMap {
    // ...
}

public class JSONArray extends ArrayList {
    // ...
}

When you call put() or add(), they are defined in the superclass, which is not parameterized properly.

What you can do is add @SuppressWarnings("unchecked") to the container.

How can I prettify my JSON?

JSON.simple cannot do this, but GSON can:

Gson gson = new GsonBuilder().setPrettyPrinting().create();


Source: stackoverflow