XStream parse JSON with no root node
Asked Answered
D

3

6

I am currently deserializing JSON using XStream, and it has been working great. However, when I have JSON string like the following

{
    key1: { an_object: { something: 'foobar' } },
    key2: { another_object: { data: 'hi' }
}

most notably it doesn't have a root node, I'm not sure how to parse it. Basically, I want the opposite of DROP_ROOT_NODE for the deserialization.

Dixie answered 11/8, 2009 at 22:33 Comment(1)
It looks like a conversation has been going about this, and it makes sense. it's based off an XML parser, and XML must contain a root node. Looks like the answer is "it can't". nabble.com/Serializing-JSON-with-no-root--td21732630.htmlDixie
A
4

The short answer is "you can't".

XStream needs to know what class to instantiate, it gets that knowledge from JSON (or XML) data. Class name can be aliased, but it can not be omitted. You can work around by:

  1. Manually wrapping your JSON string with root node containing your class name (or alias)
  2. Writing your own reader that would do it for you. However, in this case you'll still need to pass your class name (alias) to that reader either explicitly or by convention (e.g. always prepend 'root' but then configure it as alias to your class in XStream instance) - so I don't think this is any cleaner than #1.
Audile answered 11/8, 2009 at 22:57 Comment(1)
Can you provide an example of how to do option 2?Icsh
G
3

I know this is an old question, but I'll post my solution after a whole morning googling. The answer is to provide dummy root node (start and termination tags). In order to accomplish this, one of your best friends is SequenceInputStream:

My code is the following:

        reader = new XppDriver().createReader(new SequenceInputStream(
        Collections.enumeration(Arrays.asList(
        new InputStream[] {
                new ByteArrayInputStream("<PlatformAuditEvents>".getBytes()),
                new FileInputStream(file),
                new ByteArrayInputStream("</PlatformAuditEvents>".getBytes())
            }))
    ));
    in = xstream.createObjectInputStream(reader);

Here I've mixed three InputStream objects, being the first and third ones those providing the required tags missing in the file processed.

This solution was inspired by this SO Question. Hope this helps someone.

Goal answered 8/3, 2013 at 17:3 Comment(0)
G
1

Use the below code:

XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
    public HierarchicalStreamWriter createWriter(Writer writer) {
        return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
    } });
Gyrostatic answered 17/2, 2011 at 5:50 Comment(1)
What about reading JSON without a root node; is there sample code you can provide that?Cotton

© 2022 - 2024 — McMap. All rights reserved.