Closed GoogleCodeExporter closed 9 years ago
The related thread I suppose is here:
http://groups.google.com/group/google-gson/browse_frm/thread/9e654daeda6f4d9a/bb
9ce6f0a8a5708d?#bb9ce6f0a8a5708d
Steps to reproduce:
1. Initial JSON contains array:
{value1 : "value 1", value2 : ["1", "2"] }
2. Map doc = gson.fromJson( {value1 : "value 1", value2 : ["1", "2"] },
new TypeToken<Map<String, Object>>(){}.getType());
java.lang.RuntimeException: com.google.gson.JsonParseException: Type
information is unavailable, and the target object is not a primitive:
["1", "2"]
Thus GSON cannot form a Collection out of JSonArray.
However, in case then JSON is like
{value1 : "value 1", value2 : {"1", "2"} }
the above exception can be just because no Java type pointed out for {"1",
"2"}. But
["1", "2"] is a Collection (Of course, not generic collection, so type of its
elements is not known. May in this case cast to String?).
Original comment by Anton.Troshin@gmail.com
on 12 Mar 2010 at 1:42
You'll need to write a custom serializer. Here's how that looks:
static class Geo {
GeoType type;
double[] coordinates;
}
enum GeoType {
POINT, ADDRESS;
}
public static void main(String... args) {
/*
* This deserializer turns a "Point" into our GeoType enum.
* A custom deserializer required because enums are case-sensitive.
*/
JsonDeserializer<GeoType> geoTypeDeserializer = new JsonDeserializer<GeoType>() {
public GeoType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return GeoType.valueOf(json.getAsString().toUpperCase());
}
};
/*
* This deserializer turns the full object into an instance of Geo.
*/
JsonDeserializer<Geo> geoDeserializer = new JsonDeserializer<Geo>() {
public Geo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
Geo result = new Geo();
result.type = context.deserialize(jsonObject.get("type"), GeoType.class);
result.coordinates = context.deserialize(jsonObject.get("coordinates"), double[].class);
return result;
}
};
Gson gson = new GsonBuilder()
.registerTypeAdapter(GeoType.class, geoTypeDeserializer)
.registerTypeAdapter(Geo.class, geoDeserializer)
.create();
String json = "{\"type\":\"Point\",\"coordinates\":[37.43504333,-122.42824554]}";
Geo geo = gson.fromJson(json, Geo.class);
System.out.println(geo.type + " " + Arrays.toString(geo.coordinates));
}
Original comment by limpbizkit
on 28 Aug 2010 at 5:23
Custom serializer is okey, but what we really asked for is GSON to be able to
deal with ARRAYS of primitives.
Original comment by Anton.Troshin@gmail.com
on 28 Aug 2010 at 7:13
Yes, It does not solve our problem. We need it auto cast to string of array.
Original comment by laise...@gmail.com
on 4 Jun 2011 at 3:41
Original issue reported on code.google.com by
david.jonathan.nelson
on 24 Jan 2010 at 8:54