Frage

I'm new to Java. I'm trying to learn basic I/O stuff. Currently, I'm trying to figure out how to write JSON to a file. In an effort to do this, I'm using GSON.

At this time, I'm successfully generating some JSON from a HashMap. My code for that process looks like the following:

HashMap<String, String> details = new HashMap<String, String>();
details.put("Property 1", "value A");
details.put("Property 2", "value B");
details.put("Property 3", "value C");

Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String json = gson.toJson(details);

This code generates a JSON string that looks like the following:

{"Property 1":"value 1","Property 2":"value B","Property 3":"value C" }

I need to add this to a .json file on my machine. This file needs to be an array of these entries. I'm not sure how to read in an existing .json file it exists in array format and append to it. Is there a way to do that with GSON? If so, how?

Thank you

War es hilfreich?

Lösung

Look into the collection examples.

Modify your code to use collections of hash maps to serialize and deserialize.

Serialization:

Collection<HashMap<String, String>> details = new List<HashMap<String, String>>();
// add contents
String json = gson.toJson(details);

Deserialization:

String json = // read in file content
Type collectionType = new TypeToken<Collection<HashMap<String, String>>>(){}.getType();
Collection<HashMap<String, String>> details2 = gson.fromJson(json, collectionType);

In the "Collections limitations" part is written the following:

While deserializing, Collection must be of a specific generic type

I'm not sure, but that could mean, that you have to to set collectionType to use List and not Collection as specific type.

Andere Tipps

This web site shows an example with reading/wrinting simple json objects and arrays with gson.

http://examples.javacodegeeks.com/core-java/gson/convert-java-object-to-from-json-using-gson-example/

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top