2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Sireeesh, Please note that you will have to implement Serializable and override hashcode() and equals() method as well, if you ever want to retrieve data out of this.
Ya, I am doing it, It is needed for me as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.