Java 使用 GSON 创建 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26605763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:54:25  来源:igfitidea点击:

Create JSON String using GSON

javaandroidjsongson

提问by Gunaseelan

I am having a class like following,

我有一个像下面这样的课程,

public class Student {
    public int id;
    public String name;
    public int age;    
}

Now I want to create new Student,

现在我想创建新学生,

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

This gives me the following output,

这给了我以下输出,

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

So here I want String like

所以在这里我想要 String 之类的

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

If I want to edit old Student

如果我想编辑旧学生

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

Now the output is

现在输出是

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

How can I make a JSON String with a field [At some point], without a field [at some point].

如何制作带有字段 [在某些时候] 而没有字段 [在某些时候] 的 JSON 字符串。

Any help will be highly appreciable.

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

Thanks.

谢谢。

采纳答案by Pankaj Kumar

Better is to use @expose annotation like

更好的是使用@expose 注释

public class Student {
    public int id;
    @Expose
    public String name;
    @Expose
    public int age;
}

And use below method to get Json string from your object

并使用以下方法从您的对象中获取 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);
}

It will ignore id column if that is set to 0, either it will return json string with id field.

如果将 id 列设置为 0,它将忽略 id 列,或者它将返回带有 id 字段的 json 字符串。

回答by stacky

You can explore the json tree with gson.

您可以使用 gson 探索 json 树。

Try something like this :

尝试这样的事情:

gson.toJsonTree(stu1).getAsJsonObject().remove("id");

You can add some properties also :

您还可以添加一些属性:

gson.toJsonTree(stu2).getAsJsonObject().addProperty("id", "100");

回答by Seyfülislam ?zdemir

You have two options.

你有两个选择。

  • Use Java's transient keyword which is to indicate that a field should not be serialized. Gson will exclude it automatically. This may not work for you as you want it conditionally.

  • Use @Expose annotation for the fields that you want and initialize your Gson builder as following:

    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

  • 使用Java 的transient 关键字来指示不应序列化字段。Gson 会自动排除它。这可能不适合您,因为您有条件地想要它。

  • 对您想要的字段使用 @Expose 注释并初始化您的 Gson 构建器,如下所示:

    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

So you need to mark name and age fields using @Expose and you need to have two different Gson instances for the default one which includes all fields and the one above which excludes fields without @Exposeannotation.

因此,您需要使用@Expose 标记名称和年龄字段,并且您需要为默认的两个不同的 Gson 实例,其中包括所有字段,而上面的一个不包括没有@Expose注释的字段。

回答by Eugene Chipachenko

JsonObject jsObj =  (JsonObject) new Gson().toJsonTree(stu2);
jsObj.remove("age"); // remove field 'age'
jsObj.addProperty("key", "value"); // add field 'key'

System.out.println(jsObj);

You can manipulate with JsonObject

您可以使用 JsonObject 进行操作

回答by nndru

You should introduce additional field to Studentclass that will notice GSONabout idserialization policy. Then, you should implement custom serializer that will implement TypeAdapter. In your TypeAdapterimplementation according to id serialization policy you will serialize it or not. Then you should register your TypeAdapterin GSON factory:

你应该引入其他领域Student类,会发现GSON关于id序列化的政策。然后,您应该实现将实现TypeAdapter. 在您TypeAdapter根据 id 序列化策略的实现中,您将对其进行序列化或不序列化。然后你应该TypeAdapter在 GSON 工厂注册你的:

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Student.class, new StudentTypeAdapter());

Hope this helps.

希望这可以帮助。