java gson.fromJson 返回空值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37459368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
gson.fromJson return null values
提问by PAncho
This is My JSON String : "{'userName' : 'Bachooo'}"
这是我的 JSON 字符串: "{'userName' : 'Bachooo'}"
Converting JSON String to LoginVOlogic is:
将 JSON 字符串转换为LoginVO逻辑是:
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
LoginVO loginFrom = gson.fromJson(jsonInString, LoginVO.class);
System.out.println("userName " + loginFrom.getUserName()); // output null
My LoginVO.classis:
我的LoginVO.class是:
public class LoginVO {
private String userName;
private String password;
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
}
Note I am using jdk 1.8.0_92
注意我使用的是jdk 1.8.0_92
Output of loginForm.getUserName() is NULLinstead of "Bachooo"any idea about this issue?
loginForm.getUserName() 的输出是NULL不是"Bachooo"对这个问题有任何想法?
采纳答案by Vikas Madhusudana
Since you are setting excludeFieldsWithoutExposeAnnotation()configuration on the GsonBuilderyou must put @Exposeannotation on those fields you want to serialize/deserialize.
由于您正在设置excludeFieldsWithoutExposeAnnotation()配置,因此GsonBuilder您必须@Expose在要序列化/反序列化的字段上添加注释。
So in order for excludeFieldsWithoutExposeAnnotation()to serialize/deserialize your fields you must add that annotation:
因此,为了excludeFieldsWithoutExposeAnnotation()序列化/反序列化您的字段,您必须添加该注释:
@Expose
private String userName;
@Expose
private String password;
Or, you could remove excludeFieldsWithoutExposeAnnotation()from the GsinBuilder.
或者,您可以excludeFieldsWithoutExposeAnnotation()从GsinBuilder.
回答by Kumaresan Perumal
Try like this, please. Here is the example class:
请尝试这样。这是示例类:
class AngilinaJoile {
private String name;
// setter
// getter
}
And here is how you deserialize it with Gson:
下面是你如何用 Gson 反序列化它:
Gson gson = new Gson();
String jsonInString = "{'name' : 'kumaresan perumal'}";
AngilinaJoile angel = gson.fromJson(jsonInString, AngilinaJoile.class);

