我们正在使用Google GSON将JSON数据反序列化为Java对象。请参阅下面的示例JSON数据和相应的POJO类。我能够反序列化“name”和“phoneNumber”字段。但对于“deparments”字段,我看到Null。你能帮我解决一下如何反序列化“deparments”字段吗?
我的JSON:
{
"name": "customer",
"phoneNumber": "000000000",
"deparments": "xyz,abc,wyz,djkf, iii"
}
班级:
public class CustomerInfo
{
private String name;
private String phoneNumber;
private String deparments;
// getters and setters
}
CustomerDeserializer.java:
...
Gson gson = new Gson();
CustomerInfo customerInfo = gson.fromJson(reader, CustomerInfo.class);
答案 0 :(得分:1)
重新检查您的JSON来源。我认为你只有一些关键对象:depar t ,而不是 deparments 。
无论如何,下一个代码对我有用:
public class CustomerInfo
{
private String name;
private String phoneNumber;
private String deparments;
// getters and setters
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getPhoneNumber(){
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber){
this.phoneNumber = phoneNumber;
}
public String getDeparments() {
return deparments;
}
public void setDeparments(String deparments) {
this.deparments = deparments;
}
@Override
public String toString() {
return "CustomerInfo{" +
"name='" + name + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", deparments='" + deparments + '\'' +
'}';
}
}
@Test
public void desJson(){
String json = "{\n" +
" \"name\": \"customer\",\n" +
" \"phoneNumber\": \"000000000\",\n" +
" \"deparments\": \"xyz,abc,wyz,djkf, iii\"\n" +
"}";
Gson gson = new Gson();
CustomerInfo customerInfo = gson.fromJson(json, CustomerInfo.class);
System.out.println(customerInfo);
}
输出是:
CustomerInfo {name =' customer',phoneNumber =' 000000000', deparments =' xyz,abc,wyz,djkf,iii'}
答案 1 :(得分:0)
复制并粘贴以下代码
public class CustomerInfo {
@SerializedName("name")
private String name;
@SerializedName("phoneNumber")
private String phoneNumber;
@SerializedName("deparments")
private String deparments;
@Override
public String toString() {
return new Gson().toJson(this, CustomerInfo.class);
}
}
并像下面的代码一样反序列化
CustomerInfo customerInfo = new Gson().fromJson(jsonString, CustomerInfo.class);
希望这会对你有所帮助。