当类扩展GenericJson
以映射未知属性时,属性不会映射到子类中的正确属性。 json中的属性将转换为LinkedHashMap,而不是映射到实际属性。
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
public final class Employee extends GenericJson{
@Key
private String name;
@Key
private String empId;
@Key
private Address address;
}
地址类:
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
public class Address extends GenericJson{
@Key
private String state;
}
示例json:
{
"name": "Bob",
"empId": "345",
"address" : {"state" : "xyz"},
"unknownFiled" : "some value"
}
JSON到对象转换:
Employee employee = gson.fromJson(fileData, Employee.class);
@Key注释应确保属性映射到类中的变量,但在扩展GenericJson时,json字符串将转换为LinkedHashMap列表。 引发的异常如下
Exception in thread "main" java.lang.IllegalArgumentException: Can not set com.test.Address field com.test.Employee.address to com.google.gson.internal.LinkedTreeMap
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
at java.lang.reflect.Field.set(Field.java:764)
at com.google.api.client.util.FieldInfo.setFieldValue(FieldInfo.java:245)
at com.google.api.client.util.FieldInfo.setValue(FieldInfo.java:206)
at com.google.api.client.util.GenericData.put(GenericData.java:103)
at com.google.api.client.util.GenericData.put(GenericData.java:47)
at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:188)
at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:145)
at com.google.gson.Gson.fromJson(Gson.java:803)
at com.google.gson.Gson.fromJson(Gson.java:768)
at com.google.gson.Gson.fromJson(Gson.java:717)
at com.google.gson.Gson.fromJson(Gson.java:689)
at com.test.EmployeeJSONDeserlizer.main(EmployeeJSONDeserlizer.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)