discomarathon / google-gson

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

Map serialization fails #26

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. new Gson().toJson(new HashMap<String, String>());

What is the expected output?
{}

What do you see instead?
Fails with the attached exception.

What version of the product are you using? On what operating system?
gson 1.1.1
JDK 1.5, JDK 1.6

Please provide any additional information below.

Original issue reported on code.google.com by cedric.v...@gmail.com on 30 Jul 2008 at 9:57

Attachments:

GoogleCodeExporter commented 9 years ago

Original comment by joel.leitch@gmail.com on 31 Jul 2008 at 12:59

GoogleCodeExporter commented 9 years ago
You need to handle top-level "Parameterized" types differently than Class 
objects.

Due to "Type Erasure" in the Java language, when you pass in a instance of the 
"Map"
object, all generic information is lost.  To get around this problem, we 
overloaded
the toJson method to take a "Type" parameter.

Here is an example:

import com.google.gson.reflect.TypeToken;

public class TopLevelMapExample {
  public static void main(String[] args) {
    Type mapType = new TypeToken<Map<String, String>>() {}.getType();
    String json = new Gson().toJson(new HashMap<String, String>(), mapType);
    System.out.println(json);
  }
}

----

I am updating the code to throw an IllegalArgumentException with a very 
descriptive
message.

Original comment by joel.leitch@gmail.com on 31 Jul 2008 at 7:25

GoogleCodeExporter commented 9 years ago
r128 changed the code to raise a IllegalArgumentException instead.

Original comment by joel.leitch@gmail.com on 31 Jul 2008 at 7:57