gpt4 book ai didi

Java 类属性被 null json 属性覆盖

转载 作者:行者123 更新时间:2023-12-01 14:04:24 24 4
gpt4 key购买 nike

我有以下代码:

public class Member {

public int age;
public String name;
public String type = "poolMember";

public Member() {
type = "poolMember";
}
}

void newMember() {
String newMembers =
"[{\"age\":\"43\",\"name\":\"Jon\"},
{\"age\":\"25\",\"name\":\"Tom\",\"type\":\"clubMember\"}]";
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Member>>() {
}.getType();
ArrayList<Member> members = gson.fromJson(newMembers, listType);


}

public static void main(String[] args) {
newMember();
}

如果 Member.type 未在 json 字符串中定义但当前为 null,我希望它等于“poolMember”。

我知道这可以通过 instance creator 来实现但我需要帮助来实现这一点。

编辑

添加到newMember():

 System.out.println(members.get(0).type);
result = null

最佳答案

以下内容

public class Test {
static public class Member {

public int age;
public String name;
public String type = "poolMember";

public Member() {
type = "poolMember";
}

@Override
public String toString() {
return "[age = " + age + ", name = " + name + ", type = " + type
+ "]";
}
}

public static void main(String[] args) {
String newMembers = "[{\"age\":\"43\",\"name\":\"Jon\"},{\"age\":\"25\",\"name\":\"Tom\",\"type\":\"clubMember\"}]";
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Member>>() {
}.getType();
ArrayList<Member> members = gson.fromJson(newMembers, listType);

System.out.println(members);

}
}

打印

[[age = 43, name = Jon, type = poolMember], [age = 25, name = Tom, type = clubMember]]

您确定打印了正确的成员吗?

关于Java 类属性被 null json 属性覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19031660/

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