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

advertisements

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" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 70

Employee.java

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

AddressKey.java

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

}

Address.Java

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

Test.java

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

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

     AddreessKey key=new AddreessKey();
     key.setAddressId("1");
     key.setAddressName("HOME");

     Address value=new Address();
     value.setHome("home");
     value.setStreet("street");

     ax.put(key, value);

     e.setAddressMap(ax);

    //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.

HTH.