0

我有以下代码:

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

如果未在 json 字符串中定义但当前为空,我希望 Member.type 等于“poolMember”。

我知道这可以通过实例创建器来实现,但我需要帮助来实现这一点。

编辑

添加到新成员():

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

1 回答 1

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吗?

于 2013-09-26T15:17:59.747 回答