gpt4 book ai didi

java - 谷歌GSON : Deserialize JSON data to Java

转载 作者:行者123 更新时间:2023-12-01 10:22:16 28 4
gpt4 key购买 nike

我们正在使用 Google GSON 将 JSON 数据反序列化为 Java 对象。请参阅下面的示例 JSON 数据和相应的 POJO 类。我能够反序列化“name”和“phoneNumber”字段。但对于 "deparments" 字段,我看到 Null。您能帮我如何反序列化 "deparments" 字段吗?

我的 JSON:

{
"name": "customer",
"phoneNumber": "000000000",
"deparments": "xyz,abc,wyz,djkf, iii"
}

类(class):

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

最佳答案

重新检查您的 JSON 源。我认为您只有一些带有 key: departments 的对象,而不是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'}

关于java - 谷歌GSON : Deserialize JSON data to Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35507891/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com