Gson conversion problem When using the key and the value, both are user-defined objects


Hi I am facing problem when converting from json to Object when using Map with both key and value as user-defined objects, below is the example that illustrates the problem.

Error: Exception in thread "main" java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 70

public class Employee {
    private String employeeId;
    private Map<AddreessKey, Address> addressMap = new HashMap<AddreessKey, Address>();
   //Setters and getters

public class AddreessKey {
   private String addressId;
   private String addressName;
  //Getters and Setters



public class Address {
    private String street;
    private String home;
//Getters and Setters

public class Test {
    public static void main(String[] args) {
       Employee e=new Employee();

     Map<AddreessKey, Address> ax=new HashMap<AddreessKey, Address>();

     AddreessKey key=new AddreessKey();

     Address value=new Address();

     ax.put(key, value);


    //Converting to Json
    String json=new Gson().toJson(e);

   //Getting Problem When converting back to object
   //If I use Any Wrapper class or String class as key instead of object (AddreesKey), No issues when converting back to object.
  //When i use object I am getting the problem

  Employee emp=new Gson().fromJson(json,Employee.class);


Thanks In Advance, I hope my question is clear.

I ran your code and found a fix :

Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); e.setAddressMap(ax); String json=gson.toJson(e); System.out.println(" JSON :: " + json); Employee emp=gson.fromJson(json,Employee.class);

Also, be sure to use gson v2.3.1 Let me know if this does not work out for you.