Will Gson set a field to null when JSON doesn't contain it?

Andre_601 :

I actually have multiple questions regarding Gson.

The first one being if Gson would set the value of a field to null when the provided JSON does not contain any field matching it.
For example, when the provided JSON features the field name but the class I deserialize it to contains name and avatar, would avatar be null?

The next question is in relation to the above one. When I would set a field with an already predefined value, would Gson override it, even if it isn't provided in the JSON (overrides it to null) or would it simply ignore the field and move on?

And finally would I want to know if Gson would still set a value to name when I would use @SerializedName("username") but the JSON contains name.
I want to update my API, including some bad namings of JSON fields, but I want to make the transition of it for the people using it a smooth as possible, so I want to still (temporary) provide the old field name, while also providing support for the new one. Is that possible using the @SerializedName annotation?

I'm still a beginner with Gson and the Gson User Guide wasn't that helpful for me to answer those two specific questions (Or I overlooked it which would also be possible).

Smile :

I tried implementing this. Here is my code. I hope the output at the end answers your question.

JSON used:

{
  "name": "Robert",
  "weather": "19 deg"
}

Main class:

public class GSONExample2 {

    private static final String jsonStr = "JSON Mentioned above";

    public static void main(String[] args) {
        GsonDataExample root = new Gson().fromJson(jsonStr, GsonDataExample.class);
        System.out.println(root);

    }

}

POJO:

class GsonDataExample {
    @SerializedName("username")
    private String name;
    private String avatar;
    @SerializedName(value="weather", alternate = "temperature")
    private String weather;
    private String nameWithDefault = "Default name";
    // getters, setters and toString() implemented
}

Output:

GsonDataExample(name=null, avatar=null, weather=19 deg, nameWithDefault=Default name)

To map multiple keys to same attributes, you can use @SerializedName(value="weather", alternate = "temperature") as shown above.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=24397&siteId=1