0

I am searching for this for quite some time now but still, it is not clear to me. I have a JSON file which looks like this:

{
  "Name" : "Foo Bar",
  "Grade" : "Some Grade",
  "Org" : "Some Org"
}

For deserializing this JSON (using gson) I have created a Java class called StudentDetails.java which looks like this:

public class StudentDetails
{
    public String name;
    public String grade;
    public String org;
}

Now I have a couple of questions regarding this:

  1. Will gson automatically maps the fields in StudentDetails.java with corresponding keys even if the fields start with lower case and keys start from upper case in the JSON file. I have looked for @SerializedName but my code works without even using it. On the contrary if I am using something like @SerializedName("Name) with name field, it's getting assigned to null after deserialization. I am so confused right now.
  2. Will deserialization work without even getter and setter methods? In jackson you write setter and getter methods.
  3. If above is true, does it work even in the case of private fields?
Sunil Kumar
  • 390
  • 1
  • 7
  • 25
  • for 2nd it will work in gson without getter and setter, for 3rd even its private it will work for serialising and deserialising. – Ashok Kumar N Sep 26 '18 at 12:21
  • for 1st it will be case sensitive but if you annotate with @SerializedName it will work for both serialise and deserialise even you can use like this @SerializedName(value="name", alternate={"Name", "NAME"}) – Ashok Kumar N Sep 26 '18 at 12:24

1 Answers1

2
  1. I'm note sure about this one but i think the case only matters after the first character because you normally don't start the name of field with an upper-case character. Yes GSON will automatically map the fields.

  2. Yes GSON does not need getter/setter (https://stackoverflow.com/a/6203975/4622620)

  3. Yes GSON can handle private fields because it uses reflections (https://stackoverflow.com/a/28927525/4622620)

flx
  • 1,560
  • 13
  • 22
  • Thanks for the answer. Is there any documentation for the first part or any article from where I can get details about it. – Sunil Kumar Sep 26 '18 at 16:26