Java类属性被null json属性覆盖

时间:2013-09-26 14:56:11

标签: java json

我有以下代码:

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等于“poolMember”,如果它没有在json字符串中定义,但它当前为null。

我理解这可以通过instance creator来实现,但我需要帮助才能实现这一点。

修改

添加到newMember():

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

1 个答案:

答案 0 :(得分:1)

以下

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]]

您确定要正确打印members吗?