我正尝试使用google gson TypeAdapter将嵌套的JSON转换为嵌套的Java对象,并为每个类实现了TypeAdapter。但我不想在单个适配器类中编写完整的read()方法逻辑。我已经通过网络提到了几个问题和blog例子。但是完整的读取逻辑是单独的。使用gson将嵌套的JSON转换为嵌套的Java对象TypeAdapter
对于小型嵌套对象,它可以在单个Adapter中使用逻辑,但对于大对象(每个类中有超过10-15个字段),这并不好。
[更新]
例如JSON键看起来相同的类属性,但在实际我会得到输入为hyphen-separated-small-case
键,而不是Camel case
键。所以我的json和java类属性名称将不会相同,因此我必须编写我的定制逻辑进行映射。
E.g. 样品的Json输入:
{
"id": 1,
"name": "Alex",
"emailId": "[email protected]",
"address": {
"address": "21ST & FAIRVIEW AVE",
"district": "district",
"city": "EATON",
"region": "PA",
"postalCode": "18044",
"country": "US"
}
}
而Java Bean是如下:
//Employee object class
public class Employee {
private int id;
private String name;
private String emailId;
private Address address;
..
}
//Address object class
public class Address {
private String address;
private String district;
private String city;
private String region;
private String postalCode;
private String country;
..
}
我想有两个不同的适配器和在读集成多个适配器()方法。
public class EmployeeAdapter extends TypeAdapter<Employee> {
@Override
public void write(JsonWriter out, Employee employee) throws IOException {
//
}
@Override
public Employee read(JsonReader jsonReader) throws IOException {
//read logic for employee class using AddressAdapter for address json
}
}
public class AddressAdapter extends TypeAdapter<Address> {
@Override
public void write(JsonWriter out, Address address) throws IOException {
//
}
@Override
public Address read(JsonReader jsonReader) throws IOException {
//read logic for Address class
}
}
如何在EmployeeAdapter中使用AddressAdapter?
您是否尝试过使用阅读器的默认实现?或者你有特定的理由来编写自己的适配器? –
这与杰克逊有什么关系?请删除标签 –
它看起来像你只需要POJO映射,而类型适配器真的是一个矫枉过正的地方:'最终员工雇员= gson.fromJson(...,Employee.class)'似乎是完整的。 –