- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试了以下代码:
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/
我是一名优秀的程序员,十分优秀!