1

I am creating a program whereby I need to save(write) objects to a JSON, and then load(read) these objects back into the program. I have told that GSON is a good way to do this. However, I am having some troubles with it. I have tried the following:

Gson g = new Gson();
try (FileWriter writer = new FileWriter(file)) {
    String j = g.toJson(board);
    writer.write(j);  
    writer.flush();  
    writer.close();
} catch (IOException e) {
    e.printStackTrace();
}

When I run the program, I get the error:

class object3 declares multiple JSON fields named state

The object I am trying to write to the JSON has an ID, and an Array of another Object (object2), and each of these objects have an Array of another Object (object3). object3 has multiple fields, mostly strings. What is the simplest way for me to write an object such as this to a JSON file and then be able to read it back into my program?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
LondonMassive
  • 367
  • 2
  • 5
  • 20

1 Answers1

0

If you simply want to serialize and deserialize object state in a JSON format, and don't care too much about the exact shape of the JSON, XStream makes this very easy. It tolerates almost any Java object structure and isn't as pernickety as Gson.

It was originally designed to serialize to XML, but if you use the JettisonMappedXmlDriver it will output JSON instead. I have found it to be a well-written and reliable library.

Product product = new Product("Banana", "123", 23.00);
XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("product", Product.class);

System.out.println(xstream.toXML(product));

Produces:

{"product":{"name":"Banana","id":123,"price":23.0}}

To read it back in:

XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias("product", Product.class);
Product product = (Product) xstream.fromXML(json);
System.out.println(product.getName());

Prints:

Banana

ᴇʟᴇvᴀтᴇ
  • 12,285
  • 4
  • 43
  • 66