google / google/gson

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

Open
#506 6 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
24.2k
Forks
4.5k
Avg merge
6d 4h
Merged PRs (30d)
12

Description

```
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 read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
Collection 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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.