Deserializing a changing type

320 views
Skip to first unread message

tobinibot

unread,
Jan 8, 2009, 5:10:00 PM1/8/09
to google-gson
I have a situation where I will be receiving JSON from several
different sources; some may have numeric ids and some may have
alphanumeric ids. So I could receive JSON that looks like this:

[{"firstName":"Bob", "id":1000}, {"firstName":"Tim", "id":1001}]

or like this:

[{"firstName":"Bob", "id":"a01"}, {"firstName":"Tim",
"id":"b02"}]

The object I'm deserializing these into (using the default gson
deserialization) has an "id" field that is a String, so it can hold
any possible id. However, gson seems unwilling to convert from an
integer id to a String id.

com.google.gson.JsonParseException: The JsonDeserializer
StringTypeAdapter failed to deserialized json object 1000 given the
type class java.lang.String
at com.google.gson.JsonDeserializerExceptionWrapper.deserialize
(JsonDeserializerExceptionWrapper.java:63)
at
com.google.gson.JsonObjectDeserializationVisitor.visitFieldUsingCustomHandler
(JsonObjectDeserializationVisitor.java:106)
at com.google.gson.ObjectNavigator.navigateClassFields
(ObjectNavigator.java:135)
at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:116)
at com.google.gson.JsonDeserializationVisitor.visitChild
(JsonDeserializationVisitor.java:91)
at com.google.gson.JsonDeserializationVisitor.visitChildAsObject
(JsonDeserializationVisitor.java:78)
at com.google.gson.JsonArrayDeserializationVisitor.visitArray
(JsonArrayDeserializationVisitor.java:67)
at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:108)
at com.google.gson.JsonDeserializationContextDefault.fromJsonArray
(JsonDeserializationContextDefault.java:65)
at com.google.gson.JsonDeserializationContextDefault.deserialize
(JsonDeserializationContextDefault.java:47)
at com.google.gson.Gson.fromJson(Gson.java:373)
at com.google.gson.Gson.fromJson(Gson.java:321)
at com.google.gson.Gson.fromJson(Gson.java:297)

I think gson should be able to use String.valueOf for numeric types
and boolean values. I can open a ticket (and possibly provide a
patch) if this is a valid feature.

However, in the mean time, is there an quick way to get around this
problem?

Thanks.

Tobin

inde...@gmail.com

unread,
Jan 8, 2009, 7:05:16 PM1/8/09
to google-gson
I agree. Please file a bug on us and we will fix this.

Thanks
Inder
Reply all
Reply to author
Forward
0 new messages