asolfre / google-gson

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

deserializing object instead a collection with a single object into a collection #506

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
I use gson to serialize and deserialize a web service based on jaxws-json. This 
web service returns an object without having the enclosing brackets of an 
array, when it has a collection with a single objects. With jackson you have 
the option to set the deserializer to ACCEPT_SINGLE_VALUE_AS_ARRAY to meet this 
conditions. I changed gson's CollectionTypeAdapterFactory to accept an object 
instead of an array with a simple try catch code in method read. the original 
code is in the try block and reading the single object and adding it to the 
collection you will find in the catch block

    public Collection<E> read(JsonReader in) throws IOException {
      if (in.peek() == JsonToken.NULL) {
        in.nextNull();
        return null;
      }
      Collection<E> collection = constructor.construct();
      try {
          in.beginArray();
          while (in.hasNext()) {
            E instance = elementTypeAdapter.read(in);
            collection.add(instance);
          }
          in.endArray();
      } catch (Exception e) {
          E instance = elementTypeAdapter.read(in);
          collection.add(instance);
      }
      return collection;
    }

I think it is a better idea to make a serialization option and check this 
option in the catch block to propaget the exception thrown in in.beginArray() 
when not set, but I was satisfied with this simple improvement. Thx for this 
simple, but functional java json converter 

Original issue reported on code.google.com by mbreuer....@googlemail.com on 22 Mar 2013 at 4:06

GoogleCodeExporter commented 9 years ago
This seems like a bad idea. Basically, your API is not consistent for your 
clients. Sometimes, it spits out an array, sometimes it spits out the object. 
The client will need to have unnecessary code dealing with this condition.

Original comment by inder123 on 4 Apr 2013 at 9:53

GoogleCodeExporter commented 9 years ago
Unfortunately some API's are indeed not consistent. In my case it's something 
that is not possible to change.

Ability to parse single object as a collection would be a great feature for the 
GSON. It could be optional behavior that is defined with the separate flag 
(like in the JACKSON).

But again such feature would make GSON even more powerful tool in this not 
ideal world.

Please implement this request. For now I will use suggested patch. Thanks for 
the workaround!

Original comment by denys.ni...@gmail.com on 14 May 2013 at 7:21