简体   繁体   English

如何在Java中使用“默认”类属性解码json字符串?

[英]How can I decode a json string with 'default' class properties in java?

I Tried the following code: 我尝试了以下代码:

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

A new ArrayList is created containing Member 'Anne' but even with the constructor her eyecolor = null. 将创建一个新的ArrayList,其中包含成员“ Anne”,但即使使用构造函数,其eyecolor = null。

How can I achieve this? 我该如何实现?

FWIW, this may be relevant Default Value when deserialized? FWIW, 反序列化时这可能是相关的默认值吗? :

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. 如果您的类没有默认的构造函数,我相信(可能是错误的),Gson会手动尝试分配对象,这将完全跳过任何初始化。 This will actually fail on some platforms (I have seen posts to that effect about Android allocations failing). 这实际上在某些平台上会失败(我看到过有关Android分配失败的信息)。

So you should always make sure Gson-constructed classes have a default constructor . 因此,您应始终确保Gson构造的类具有默认构造器 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. 将您显示在默认构造函数中的代码起作用的原因可能不是因为您移动了代码,而是因为根本没有默认构造函数。

I tried your code (Gson 2.2.4, JVM 1.7 on Windows), but in your example blue was not defined at all. 我尝试了您的代码(Windows上为Gson 2.2.4,JVM 1.7),但是在您的示例中, blue根本没有定义。 I defined: 我定义了:

 public static final String blue = "BLUE";

and so I got this result: 所以我得到了这个结果:

 Member [age=43, name=Anne, eyeColor=BLUE]

So I suspect that blue is defined somewhere but is not initialized since I checked that the default constructor is called. 因此,我怀疑在某处定义了blue但由于检查了默认构造函数已被调用而未初始化。 I added also an int ivar to Members and is setup to 0. 我还向Members添加了一个int ivar,并将其设置为0。

Gson create Members using newInstance method (roughly calling new Member() ), if you want pass some values during construction of object, you need to use an InstanceCreator . GSON创建Members使用newInstance方法(大致调用new Member()如果你想建设目标的过程中通过一些值,你需要使用一个InstanceCreator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM