Please check the XStream - Quick start tutorial. The only difference is in the line with the initialization:

XStream xStream = new XStream(new JsonHierarchicalStreamDriver());

The output is as follows:

{"contact": {
  "name": "Cristian Sulea",
  "addresses": [
    {
      "street": "My Street",
      "city": "Bucharest"
    },
    {
      "street": "Another Street",
      "city": "Bucharest"
    }
  ]
}}

Dropping the root

Sometimes the root node in the generated JSON is superfluous, since its name is caused by the Java type of the written object that has no meaning in JSON and increases only the nesting level of the structure. Therefore it is possible to drop this root by initializing the internally used JsonWriter in a different mode.

Again, the only difference is in the initialization:

XStream xStream = new XStream(new JsonHierarchicalStreamDriver() {
  public HierarchicalStreamWriter createWriter(Writer writer) {
    return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
  }
});

The output is as follows:

{
  "name": "Cristian Sulea",
  "addresses": [
    {
      "street": "My Street",
      "city": "Bucharest"
    },
    {
      "street": "Another Street",
      "city": "Bucharest"
    }
  ]
}

Read from JSON

Contact contact = (Contact) xStream.fromXML(json);

Categories & Tags


Related


Share