10

There is a lot information at stackoverflow about how to deserialize a json array using Gson.

But how can I do the same using XStream with jettison?

Here is json:

{"entity":[{"id":"1", "name":"aaa"}, {"id":"2", "name":"bbb"}]}

Here is XStream code how I try to parse it:

XStream xstream = new XStream(new JettisonMappedXmlDriver());
xstream.alias("entity", Entity[].class);
return (Entity[])xstream.fromXML(jsonString);

I have following exception:

com.thoughtworks.xstream.converters.ConversionException: id : id
lakshman
  • 2,641
  • 6
  • 37
  • 63
Misha
  • 828
  • 10
  • 23
  • 1
    I like XStream very much. You can see I'm ranked as the 6th user at the XStream answer tag. I tried to solve your problem using XStream all the ways I could think of and I have failed. There is another thread listing other libraries to work with JSON here: http://stackoverflow.com/questions/5245840/how-to-convert-string-to-jsonobject-in-java . I am sorry! – pablosaraiva Sep 30 '13 at 21:24
  • Were you able to get this working? Did you try: `xstream.alias("entity", Entity.class);` with `xstream.addImplicitCollection(Entity.class, "entity");` and using a `List` instead of an array? – Kenny Linsky Sep 30 '15 at 21:49

2 Answers2

0

As can be seen from this answer related to root element XStream fails when there is not root element in JSON.

Once you map entity to certain Java class XStream cannot find root element for pairs of id and name (as in JSON they are not enclosed in element).

Only hand-made wrapper, manipulating input streams or using custom converter can help here.

Community
  • 1
  • 1
flaz14
  • 826
  • 1
  • 13
  • 25
0

With array I cannot get it running, but with a list:

Java:

package de.mosst.spielwiese;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

import lombok.Data;

public class XStreamDeserializeJsonWithJettison {

    @Test
    @SuppressWarnings("unchecked")
    public void smokeTest() {
        InputStream file = XStreamDeserializeJsonWithJettison.class.getResourceAsStream("XStreamDeserializeJsonWithJettison.json");
        XStream xStream = new XStream(new JettisonMappedXmlDriver());
        xStream.processAnnotations(Entity.class);

        List<Entity> entities = (List<Entity>) xStream.fromXML(file);
        System.out.println(entities);
    }

    @Data
    @lombok.AllArgsConstructor
    @XStreamAlias("entity")
    class Entity {
        String id;
        String name;
    }
}

XML:

{
    "list": [
        {
            "entity": [
                {
                    "id": 1,
                    "name": "odin"
                },
                {
                    "id": 2,
                    "name": "dwa"
                }
            ]
        }
    ]
}
Mark
  • 17,887
  • 13
  • 66
  • 93