Gson 转换问题当使用 Key 和 Value 都是用户定义的对象时

Gson Conversion Issue When using Key and Value both are User defined Objects

您好,我在将 Map 与键和值都用作用户定义对象时从 json 转换为对象时遇到问题,下面是说明问题的示例。

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);


  }
}

提前致谢,我希望我的问题很清楚。

我 运行 你的代码并找到了一个修复:

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);

另外,一定要使用gson v2.3.1 如果这不适合您,请告诉我。

HTH.