加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 使用GSON创建JSON字符串

发布时间:2020-12-14 17:43:46 所属栏目:Java 来源:网络整理
导读:我正在下课, public class Student { public int id; public String name; public int age; } 现在我想创建新的学生, //while create new studentStudent stu = new Student();stu.age = 25;stu.name = "Guna";System.out.println(new Gson().toJson(stu));
我正在下课,
public class Student {
    public int id;
    public String name;
    public int age;    
}

现在我想创建新的学生,

//while create new student
Student stu = new Student();
stu.age = 25;
stu.name = "Guna";
System.out.println(new Gson().toJson(stu));

这给我以下输出,

{"id":0,"name":"Guna","age":25} //Here I want string without id,So this is wrong

所以这里我想要String

{"name":"Guna","age":25}

如果我想编辑老学生

//While edit old student
Student stu2 = new Student();
stu2.id = 1002;
stu2.age = 25;
stu2.name = "Guna";
System.out.println(new Gson().toJson(stu2));

现在的输出是

{"id":1002,"age":25} //Here I want the String with Id,So this is correct

如何使用一个字段[某些时候]创建JSON字符串,没有字段[在某个时间点].

任何帮助将是非常可观的.

谢谢.

解决方法

更好的是使用@expose注释
public class Student {
    public int id;
    @Expose
    public String name;
    @Expose
    public int age;
}

并使用以下方法从对象中获取Json字符串

private String getJsonString(Student student) {
    // Before converting to GSON check value of id
    Gson gson = null;
    if (student.id == 0) {
        gson = new GsonBuilder()
        .excludeFieldsWithoutExposeAnnotation()
        .create();
    } else {
        gson = new Gson();
    }
    return gson.toJson(student);
}

如果设置为0,它将忽略id列,否则将返回带有字段的json字符串.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读