[GSON] fromJson with no-attribut element

94 views
Skip to first unread message

yodamad

unread,
Apr 11, 2012, 7:22:33 AM4/11/12
to google-gson
Hi,

i'm trying to extract data from a json file but ther's a weird part
in it.
Here is an exemple :

"members":[
"name":"John",
"email":"jo...@gson.com"
{"children":[{"name":"Bob}]},
{"address":"Melrose Place",
"city":"Los Angeles",
"state":"CA"}]

How can I extract to an Address object the part {"address":"Melrose
Place", "city":"Los Angeles", "state":"CA"} as it doesn't have an
attribute name.

In my Member class, I cannot annotate the address attribute with
@SerializedName because I don't have an name for it.

Is there a way to add this mapping to serialization context ?

Thanks in advance,
Matthieu

Brandon Mintern

unread,
Apr 11, 2012, 3:44:39 PM4/11/12
to googl...@googlegroups.com
This is malformed JSON. The problems:

1. In order to have "key: value" pairs, the elements need to be within
an object (i.e., {...}). The toplevel JSON needs to be wrapped in {}.
The object mapped to "members" cannot be a list (i.e., [...]), but
must be an object (i.e., {...}), because it contains, e.g., "name":
"John".

2. There must be a comma after every "key: value" pair;
"js...@gson.com" should have a comma after it.

3. A bare value CANNOT be part of an object; you cannot have {"email":
"jo...@gson.com", {...}}. The thing after the comma MUST be "name":
{...}.

4. A quote must ALWAYS be matched. The child named "Bob" is missing a
closing quote.

In order for this JSON to be useful at all, it has to be in a valid
form, something like this:

String json = "{'members':[" +
"{'name':'John'," +
" 'email':'jo...@gson.com'," +
" 'children':[{'name':'Bob'}]," +
" 'address':{'street':'Melrose Place'," +
" 'city':'Los Angeles'," +
" 'state':'CA'}}]}";

Then you can parse it with objects like this:

class Members {
Member[] members;
}

class Member {
String name;
String email;
Child[] children;
Address address;
}

class Child {
String name;
}

class Address {
String street;
String city;
String state;
}

and finally...

Members members = new Gson().fromJson(json, Members.class);

Note that you'll then be able to say:

String json = new Gson().toJson(members);

in order to get back the JSON string that I specified above.

Does that make sense? I'll be happy to help you with anything else
that's unclear.

Reply all
Reply to author
Forward
0 new messages