0

I have a problem with gson deserialization. Incoming json looks like this {"roles":{"name":"bla" "perm" : "bla"}} or when there is more roles available it looks like this {"roles":[{"name":"bla" "perm" : "bla"}{"name":"hihi" "perm" : "hihi"}]}. So first time parameter roles is an object and second time it's an array of objects.

Problem occures when my java class has field Role[] roles; and in json parametr roles is just one object exception is thrown "Expected BEGIN_ARRAY but was BEGIN_OBJECT".

Thank you in regards

Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
malinjir
  • 1,475
  • 2
  • 12
  • 17

2 Answers2

1

This is a bit bogous situation - you can't expect that the library will handle properly two different schemas for the json in the same time. However I had similar problem when my clients used GSON for consuming the services, but they were configured using Jersey.

Adding Jackson along with the proper configuration made my services serve always an array which is the actual fix of the problem. See this thread for explanation of how you can fix the service.

Community
  • 1
  • 1
Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • Thank you for your post. Problem is that I do not have an access to server side of this application:(. – malinjir Apr 14 '12 at 10:59
  • 1
    Hmm maybe switch to using Jacksoon instead of GSON then? after all these libraries declare such inconsistent handling of arrays, so they should be at least able to handle their own output. – Boris Strandjev Apr 14 '12 at 11:03
1

You could use your own TypeAdapter which handles the single instance case, deserializes it and then transform into an array and set it on the field, making it uniform.

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117