嗨我在使用带有键和值作为用户定义对象的Map时从json转换为Object时遇到问题,下面是说明问题的示例。
错误:线程“main”com.google.gson.JsonSyntaxException中出现异常: java.lang.IllegalStateException:预期为BEGIN_OBJECT但是为STRING 在第1栏第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);
}
}
先谢谢,我希望我的问题很清楚。
答案 0 :(得分:2)
我运行了您的代码并找到了修复程序:
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。