gson.fromJson return null values

21,020

Since you are setting excludeFieldsWithoutExposeAnnotation() configuration on the GsonBuilder you must put @Expose annotation on those fields you want to serialize/deserialize.

So in order for excludeFieldsWithoutExposeAnnotation() to serialize/deserialize your fields you must add that annotation:

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

Or, you could remove excludeFieldsWithoutExposeAnnotation() from the GsonBuilder.

Share:
21,020
PAncho
Author by

PAncho

Updated on September 03, 2020

Comments

  • PAncho
    PAncho over 3 years

    This is My JSON String : "{'userName' : 'Bachooo'}"

    Converting JSON String to LoginVO logic is:

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

    My LoginVO.class is:

    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

    Output of loginForm.getUserName() is NULL instead of "Bachooo" any idea about this issue?

    • OneCricketeer
      OneCricketeer almost 8 years
      And what happens if you only use Gson gson = new Gson()?
    • PAncho
      PAncho almost 8 years
      if i only use Gson gson = new Gson() Infinity loop at recursive calling com.google.gson.internal.$Gson$Types.resolve($Gson$Types.jav‌​a:375)
    • Braj
      Braj almost 8 years
      what excludeFieldsWithoutExposeAnnotation says? "only expose fields that are annotated and ignore the rest "
    • Siguza
      Siguza almost 8 years
      Possible duplicate of How should I escape strings in JSON?
    • Siguza
      Siguza almost 8 years
      ^ i.e. single quotes are not valid JSON.
  • PAncho
    PAncho almost 8 years
    Thanks man its work 100% all I need @Expose To my variable i need to initialized.
  • Vikas Madhusudana
    Vikas Madhusudana almost 8 years
    Or the other option is to just say new GsonBuilder().create() if you dont have access to edit the class