minh93 / google-gson

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

toJson converts map's Integer key into a String #589

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. Construct a Map with Integer key
2. Put key/value pair into the map, making sure the key is an Integer
3. Write JSON stream using toJson to convert the map to JSON
4. Check the output file

What is the expected output? What do you see instead?
Expect to see the key represented as an Integer with no quotes. The key is 
represented as a String with double quotes.

What version of the product are you using? On what operating system?
Goobuntu. The latest in third_party/java.

Please provide any additional information below.
Might have the same root cause as issue 524, but I'm seeing the problem in 
toJson instead of fromJson.

Here's some sample code to demonstrate the bug:

private void writeJsonStreamTest(OutputStream out) throws IOException {
  JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
  writer.setIndent("  ");
  writer.beginArray();
  Map<Integer, String> data = new HashMap<Integer, String>();
  data.put(new Integer(4), "Hello");
  new Gson().toJson(data, HashMap.class, writer);
  writer.endArray();
  writer.close();
}

Here's the actual output from calling that method:
[
  {
    "4": "Hello"
  }
]

Expected this instead:
[
  {
    4: "Hello"
  }
]

Original issue reported on code.google.com by vivienne...@google.com on 19 Aug 2014 at 5:29

GoogleCodeExporter commented 9 years ago
As yonmost pointed out in issue 524, if the Integer is a value instead of key 
then it works as expected. I swapped the Integer and String in the data map 
above, and got this expected output:

[
  {
    "Hello": 4
  }
]

Original comment by vivienne...@google.com on 19 Aug 2014 at 5:32

GoogleCodeExporter commented 9 years ago
My colleague pointed out that JSON keys have to be Strings. Would it be 
possible then to add documentation in toJson so the end user doesn't get 
confused when trying to parse the JSON back into a Map?

Original comment by vivienne...@google.com on 19 Aug 2014 at 5:58

GoogleCodeExporter commented 9 years ago
You should use

new Gson().toJson(data, new TypeToken<Map<Integer, String>>() {}.getType())

Otherwise, gson can't know what kind of map you want.

http://google-gson.googlecode.com/svn/tags/1.1.1/docs/javadocs/com/google/gson/r
eflect/TypeToken.html

Original comment by Maaarti...@gmail.com on 27 Aug 2014 at 3:54

GoogleCodeExporter commented 9 years ago
"new Gson().toJson(data, new TypeToken<Map<Integer, String>>() {}.getType())"
The above method is not work.

Original comment by androida...@gmail.com on 31 Dec 2014 at 4:15