discomarathon / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

How do I deserialize when the result is sometimes an object and sometimes an array #200

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago

I am trying to deserialize a json object which sometimes comes in the form of 
an array of objects 
and sometimes it's the object itself. Is there a way of handling these 
situations.

eg
"Categories":{"Category":[{"id":"96926148","content":"Food Delivery 
Services"},{"id":"96926234","content":"Carry Out & Take 
Out"},{"id":"96926238","content":"Sandwiches"},{"id":"96926242","content":"Fast 
Food"},{"id":"96926243","content":"Pizza"}]}

and sometimes

"Categories":{"Category":{"id":"96926148","content":"Food Delivery Services"}}

Original issue reported on code.google.com by james.st...@epochsg.com on 4 Apr 2010 at 3:54

GoogleCodeExporter commented 9 years ago
I know this doesn't directly answer the question, but would it make more sense 
to 
always have an array in the JSON?  It seems like the data structure in your 
example 
makes things more difficult for both the JavaScript and Java.

I would probably try using two different beans on the Java side.  Try one first 
and 
see if it throws a Gson exception, then try the other one.  Quick and dirty, 
maybe 
not the best solution.

Original comment by joshuadr...@gmail.com on 5 Apr 2010 at 12:51

GoogleCodeExporter commented 9 years ago
I would definitely agree with your comment although I don't have any control 
over the incoming JSON.

Original comment by james.st...@epochsg.com on 5 Apr 2010 at 1:27

GoogleCodeExporter commented 9 years ago
I think you want to create a custom JsonDeserializer<List<Category>>.

That deserializer should check whether the passed-in object is a JsonArray 
(isJsonArray()) and if so, loop over the contents, converting each to a 
Category using the passed-in JsonDeserializationContext.

Otherwise it should convert the lone object to a Category, also with the 
JsonDeserializationContext.

Original comment by limpbizkit on 28 Aug 2010 at 5:33