1
votes

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?

1
If you mean by "What is the best?", that you want the fastest, you can have a look at Boon: rick-hightower.blogspot.be/2014/01/…Wim Deblauwe
@WimDeblauwe Please link me some examples.spongebob
How do you declare array?Code-Apprentice
Before you do anything, go to json.org and study the JSON syntax -- it only takes 5-10 minutes to learn, and without it you're lost. Then understand that a JSON "object" is equivalent to a Java "Map", while a JSON "array" is equivalent to a Java "List". The various JSON toolkits for Java either map JSON to existing Map and List classes or implement their own. Learn how to work with the Map and List representation before you get talked into using Jackson or whatnot which maps JSON to "POJOs" (arbitrary Java objects), as that is a much more complex way to deal with things.Hot Licks
@Code-Apprentice See the code.spongebob

1 Answers

2
votes

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();