stanfy / gson-xml

Java library for XML deserialization
Apache License 2.0
199 stars 41 forks source link

BEGIN_OBJECT expected, but met NAME #33

Open paakjis opened 5 years ago

paakjis commented 5 years ago

Hi.

I'm having an issue while parsing an XML api response.

It's similar to this issue, but I can't change the XML like he did.

What am I doing wrong ?

My Error:

Process: myproject.com, PID: 26672
    com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: BEGIN_OBJECT expected, but met NAME
    Scopes: INSIDE_OBJECT>NAME>INSIDE_OBJECT>INSIDE_EMBEDDED_ARRAY>INSIDE_OBJECT>NAME
    Closed tags: 'person'/2
    Token: null
    Tokens queue: null
    Values queue: person, null

My XML:

<website>
    <person>
        <id_person>60</id_person>
        <name>Peter</name>
        <personal_items>
            <item>
                <id>165</id>
                <name>Phone</name>
            </item>
            <item>
             ...
            </item>
        </personal_items>
    </person>
    <person>
    ...
    </person>
</website>

My Model:

public class Persons {
    private List<Person> person;    
    //getters
}
public class Person {
    String id_preson;
    String name;
    PersonalItems personal_items;
    //getters
}
public class PersonalItems{
    List<Item> item;
    //getters
}
public class Item{
    String id;
    String name;
    //getters
}

My Java code:

XmlParserCreator parserCreator = new XmlParserCreator() {
                @Override
                public XmlPullParser createParser() {
                    try {
                        return XmlPullParserFactory.newInstance().newPullParser();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            };
GsonXml gsonXml = new GsonXmlBuilder()
                    .setXmlParserCreator(parserCreator)
                    .setSameNameLists(true)
                    .create();

Persons persons = gsonXml.fromXml(xml, Persons.class);
paakjis commented 5 years ago

It's interesting. I replaced string "<item>" to "<item id="">". And it works. Looks like it is waiting for id. Even tho all the id's are empty it works. xml = xml.replace("<item>", "<item id=\"\">");

So after I replace, it looks like this:

<website>
    <person>
        <id_person>60</id_person>
        <name>Peter</name>
        <personal_items>
            <item id="">
                <id>165</id>
                <name>Phone</name>
            </item>
            <item id="">
             ...
            </item>
        </personal_items>
    </person>
    <person>
    ...
    </person>
</website>

I'm not closing, because its kind of a hack. Still would like to know what I'm doing wrong.

Now it looks like the API XML is wrong. They gave me a choice between broken JSON or this XML. Seems like I'll be working with XML.