简体   繁体   English

gson在反序列化JSON时如何将JSON键与Java类中的字段映射

[英]How does gson maps JSON keys with the fields in Java classes while deserializing the JSON

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: 我有一个看起来像这样的JSON文件:

{
  "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: 对于反序列化JSON这(使用GSON)我创建了一个称为一个Java类StudentDetails.java看起来像这样:

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. 会自动GSON在田里映射StudentDetails.java与相应的按键,即使领域开始与小写键从JSON文件上的情况下启动。 I have looked for @SerializedName but my code works without even using it. 我一直在寻找@SerializedName但是我的代码甚至都没有使用它。 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. 相反,如果我在名称字段中使用@SerializedName("Name)类的东西,则在反序列化后将其分配为null。我现在很困惑。
  2. Will deserialization work without even getter and setter methods? 反序列化是否可以使用甚至没有getter和setter方法的方法? In jackson you write setter and getter methods. 在杰克逊中,您编写了setter和getter方法。
  3. If above is true, does it work even in the case of private fields? 如果上述情况是正确的,那么即使在私有字段中也可以使用吗?
  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. 是的, GSON将自动映射字段。

  2. Yes GSON does not need getter/setter ( https://stackoverflow.com/a/6203975/4622620 ) GSON 不需要的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 ) 是的,因为GSON使用反射,所以它可以处理私有字段( https://stackoverflow.com/a/28927525/4622620

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM