使用Google GSON库对Java模型类使用Annotation

时间:2014-01-02 15:54:07

标签: java android json annotations gson

我在Android应用程序中有一个Java模型类。我需要以Json格式将此类的对象发送到C#(WCF)中的Web服务。

public class Version {

    private String Core;
    private String FastInspektion;

    public String getCore() {
        return Core;
    }

    public void setCore(String core) {
        this.Core = core;
    }

    public String getFastInspektion() {
        return FastInspektion;
    }

    public void setFastInspektion(String fastInspektion) {
        this.FastInspektion = fastInspektion;
    }

他们在C#中使用大写字母表示首字母,但在java中我们使用小写字母。如何在java中使用Annotation以便将我的字段更改为小写,例如核心而不是Core等?

Json创作者:

this.gson = new GsonBuilder().create();
obj = new Version();
obj.setCore("lab lab...");
obj.setFastInspektion("lab lab...");
gson.toJson(newobj);

2 个答案:

答案 0 :(得分:2)

使用Gson,您可以使用@SerializedName为您的字段添加注释,以便为其提供不同的JSON名称。 (你说这个类是用Java编写的,但你的字段名是大写的。)

通常

private String core;

会产生

{"core":"some value"}

相反,请使用

@SerializedName("Core")
private String core;

产生

{"Core":"some value"}

答案 1 :(得分:1)

@SerializedName("Core") private String Core;
@SerializedName("FastInspektion") private String FastInspektion;

正如here所述,注释与类成员一起使用。另请注意,在Java中,通常字段成员(和其他变量)以小写字母开头。