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.
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.
By specifying @SerializedName , GSON will not look in json based on variable name & will just use specified @SerializedName .
@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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With