AiorosXu / google-gson

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

Should support custom serializers for map keys #127

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
This is actually a RFE for supporting custom serializers for map keys, the 
current implementation 
relies on result of String.valueOf for map keys, but if I've registered a 
custom serialization type 
adapter for the type of map key it (obviously) doesn't get called

What steps will reproduce the problem?
create any class with toString method and register a JsonSerializer for it, try 
to serialize to JSON, 
you'll see the toString method beeing called instead of the registered 
serializer

What is the expected output? What do you see instead?
a call to JsonSerializer instead to toString method, and result from the 
serializer in the JSON 
output

What version of the product are you using? On what operating system?
gson 1.4 on OSX Leopard 10.5.7

Please provide any additional information below.
patch is attached, with a possible solution that calls into serialization 
context while honoring 
current implementation's behavior for keys without registered serializers, and 
a unit test for the 
specific situation

Original issue reported on code.google.com by zregv...@gmail.com on 31 May 2009 at 6:30

Attachments:

GoogleCodeExporter commented 9 years ago
The reason Gson doesn't allow custom handlers for Map Keys is because the key 
needs to 
be a valid field name (it can not be a Json object, for example). Allowing 
arbitrary 
handlers can result in invalid JSON being produced.I understand that using 
toString() 
is probably unnaturally limited, but supporting serializers is not a good idea. 
Any 
other proposals? 

Original comment by inder123 on 2 Jun 2009 at 5:46

GoogleCodeExporter commented 9 years ago
Yes, this was quick and dirty support custom serializers as it expects (JSON) 
String to be returned from the 
serializers; I see two other possible solutions, either have the key objects 
implement something like JsonMapKey 
interface with String asMapKey() method, or have specialized type for custom 
map key serializers. One thing to 
note is that deserialization for custom map key objects is currently supported, 
so one would hope that 
serialization would be supported trough the same mechanism.
Overall this is not a big issue as one can implement toString() method and 
preform serialization there...

Original comment by zregv...@gmail.com on 3 Jun 2009 at 12:56

GoogleCodeExporter commented 9 years ago
The reason we do not support serialization is because we do not want to output 
invalid 
JSON. Deserialization is supported to be more permissive in what input we 
accept.

Original comment by inder123 on 3 Jun 2009 at 5:46

GoogleCodeExporter commented 9 years ago

Original comment by inder123 on 23 Sep 2009 at 7:08