gson.fromJson返回空值

时间:2016-05-26 11:19:24

标签: 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

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

}

注意我正在使用 jdk 1.8.0_92

对于这个问题,loginForm.getUserName()的输出是NULL而不是"Bachooo"

2 个答案:

答案 0 :(得分:3)

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

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

@Expose
private String userName;
@Expose
private String password;

或者,您可以从excludeFieldsWithoutExposeAnnotation()删除GsinBuilder

答案 1 :(得分:-1)

请试试。你使用Gson jar来运行它。

     class AngilinaJoile{

     private String name;

     Here you generate setter and getter methods.

     setter..

     getter..  
     }

    Gson gson = new Gson();  

    String jsonInString = "{'name' : 'kumaresan perumal'}";

    AngilinaJoile angel = gson.fromJson(jsonInString, AngilinaJoile.class);
相关问题