Ali
Ali

Reputation: 9994

Use Annotation for Java model class using Google GSON library

I have a Java model class in an android app. I need to send an object of this class in Json format to a Web Service in C# (WCF).

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

They are using uppercase for first letters in C#, but in java we use lowercase. How can I use Annotation in java in order to change my fields to lowercase such as core instead of Core and etc?

Json creator:

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

Upvotes: 0

Views: 1582

Answers (2)

einnocent
einnocent

Reputation: 3974

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

As described here, the annotation goes with the class member. Note also that in Java, typically field members (and other variables) begin with a lower-case letter.

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279990

With Gson, you can annotate your field with @SerializedName to give it a different JSON name. (You say the class is in Java, but your field names are capitalized.)

Typically

private String core;

would produce

{"core":"some value"}

Instead, use

@SerializedName("Core")
private String core;

which produces

{"Core":"some value"}

Upvotes: 2

Related Questions