简体   繁体   中英

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.

How can I achieve this?

FWIW, this may be relevant 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.

I tried your code (Gson 2.2.4, JVM 1.7 on Windows), but in your example blue was not defined at all. 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. I added also an int ivar to Members and is setup to 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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