gson.fromJson返回空值

PAn*_*cho 6 java json object gson

这是我的JSON字符串: "{'userName' : 'Bachooo'}"

将JSON字符串转换为LoginVO逻辑是:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
LoginVO loginFrom  = gson.fromJson(jsonInString, LoginVO.class);
System.out.println("userName " + loginFrom.getUserName()); // output null
Run Code Online (Sandbox Code Playgroud)

我的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;
 }

}
Run Code Online (Sandbox Code Playgroud)

注意我使用的是jdk 1.8.0_92

loginForm.getUserName()的输出是否有关于此问题NULL"Bachooo"任何想法?

Vik*_*ana 8

由于您在 上设置excludeFieldsWithoutExposeAnnotation()配置,因此GsonBuilder必须@Expose在要序列化/反序列化的字段上添加注释。

因此,为了excludeFieldsWithoutExposeAnnotation()序列化/反序列化您的字段,您必须添加该注释:

@Expose
private String userName;
@Expose
private String password;
Run Code Online (Sandbox Code Playgroud)

或者,您可以excludeFieldsWithoutExposeAnnotation()GsonBuilder.