PAncho
PAncho

Reputation: 341

gson.fromJson return null values

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?

Upvotes: 10

Views: 25664

Answers (3)

Divyanshu Singh
Divyanshu Singh

Reputation: 87

Adding what resolved this for me. So in my API following gson implementation was getting used:

Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

I had to use the same implementation in my test, before which gson was failing to parse attributes.

So in essence check how your gson is configured in api/handler, and use same configuration in your test.

Upvotes: 0

Vikas Madhusudana
Vikas Madhusudana

Reputation: 1482

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.

Upvotes: 8

Kumaresan Perumal
Kumaresan Perumal

Reputation: 1956

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 = new Gson();  
String jsonInString = "{'name' : 'kumaresan perumal'}";
AngilinaJoile angel = gson.fromJson(jsonInString, AngilinaJoile.class);

Upvotes: -2

Related Questions