gpt4 book ai didi

java - 如何在java中解码具有 'default'类属性的json字符串?

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

我尝试了以下代码:

public class Member{
int age;
String name;
String eyeColor = blue;


Member (){
eyeColor = blue;
}
}

String newMembers="[{\"age\":\"43\",\"name\":\"Anne\"}]";

Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Member>>() {}.getType();
ArrayList<Member> nMembrs = gson.fromJson(newMembers, listType);

创建了一个包含成员“Anne”的新 ArrayList,但即使使用构造函数,她的 eyecolor = null。

我怎样才能实现这个目标?

最佳答案

FWIW,这可能相关 Default Value when deserialized? :

If your class has a default constructor (even an empty one), your first pattern (initializing the instances variables where they are defined instead of in the constructor) should work fine. If your class does not have a default constructor, I believe (I could be wrong) that Gson manually tries to allocate the object, which would skip any initialization at all. This will actually fail on some platforms (I have seen posts to that effect about Android allocations failing).

So you should always make sure Gson-constructed classes have a default constructor. It may be that putting the code you showed in the default constructor worked not because you moved the code around, but because you had a default constructor at all.

关于java - 如何在java中解码具有 'default'类属性的json字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18969599/

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