Cannot serialize or deserialize Maps with complex keys
See original GitHub issueimport java.util.HashMap;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GsonTest {
public static void main(String[] args) {
new GsonTest();
}
public GsonTest() {
HashMap<ComplexKey, String> map = new HashMap<ComplexKey, String>();
map.put(new ComplexKey("Test1", "Test2"), "Value1");
Gson gson = new Gson();
System.out.println(gson.toJson(map, new TypeToken<HashMap<ComplexKey,
String>>(){}.getType()));
}
public class ComplexKey {
private String keyOne;
private String keyTwo;
public ComplexKey(String keyOne, String keyTwo) {
this.keyOne = keyOne;
this.keyTwo = keyTwo;
}
public String getKeyOne() {
return keyOne;
}
public void setKeyOne(String keyOne) {
this.keyOne = keyOne;
}
public String getKeyTwo() {
return keyTwo;
}
public void setKeyTwo(String keyTwo) {
this.keyTwo = keyTwo;
}
}
}
Expected Output:
{"{"keyOne":"Test1","keyTwo":"Test2"}":"Value1"}
Actual Output:
{"GsonTest$ComplexKey@1172e08":"Value1"}
Original issue reported on code.google.com by rev...@paradise.net.nz
on 25 May 2010 at 2:53
Issue Analytics
- State:
- Created 9 years ago
- Comments:13
Top Results From Across the Web
Deserializing map key with Gson expects an object
I found the following while trying to solve this puzzle: Issue 210: Cannot serialize or deserialize Maps with complex keys. For any internet...
Read more >Genson serialization for maps with complex keys
While I'm trying to serialize a map with Keys as complex java objects into json string, and then deserialize them back to java...
Read more >Map Serialization and Deserialization with Jackson - Baeldung
A quick and practical guide to serializing and deserializing Java Maps using Jackson.
Read more >Simple 2.7.1 - Simple XML Serialization
The element map annotation can be used with both primitive and composite objects. For example take the following XML document. <properties> <property key="one"> ......
Read more >Kotlin Map Serialization and Deserialization with Jackson
It won't throw any error, but by default, the mapper will serialize our map key Movie as a String by using toString method...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Original comment by
jakewhar...@gmail.com
on 9 Jan 2013 at 8:29enableComplexMapKeySerialization() is a great help and should be default. Thanx for the hint!