Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Alias for Field Names

Tags:

java

gson

Say I have an Object:

Object A
    String field1 = "abc";
    String field2 = "xyz";

The json for the above is:

{
    "ObjectA": {
      "field1": "abc",
      "field2": "xyz"
    }
}

I was trying to create a new id for the field names before sending the json. E.g. "field1" to be called "f1" and "field2" to be called "f2". So the intended output json is shown below:

{
    "ObjectA": {
      "f1": "abc",
      "f2": "xyz"
    }
}

I am not sure how to do this. Can the above be done in a clean way? Thanks for your help and pointers.

I am using gson.

like image 853
userDSSR Avatar asked Oct 31 '15 23:10

userDSSR


People also ask

What is@ SerializedName in android?

The @SerializedName annotation can be used to serialize a field with a different name instead of an actual field name. We can provide the expected serialized name as an annotation attribute, Gson can make sure to read or write a field with the provided name.

What is@ SerializedName in Gson?

By specifying @SerializedName , GSON will not look in json based on variable name & will just use specified @SerializedName .

What is @SerializedName in spring boot?

@SerializedName annotation indicates that the annotated member should be serialized to JSON with the provided name value in the annotation attribute. This annotation will override any FieldNamingPolicy , including the default field naming policy, that may have been using the GsonBuilder class.

Is Gson better than Jackson?

ConclusionBoth Gson and Jackson are good options for serializing/deserializing JSON data, simple to use and well documented. Advantages of Gson: Simplicity of toJson/fromJson in the simple cases. For deserialization, do not need access to the Java entities.


1 Answers

Use the annotation @SerializedName("name") on your fields. Like this:

Object A @SerializedName("f1") String field1 = "abc"; @SerializedName("f2") String field2 = "xyz"; 

See https://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html.

like image 61
Jesper N Avatar answered Sep 21 '22 13:09

Jesper N