Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 423
PAncho Avatar asked May 26 '16 11:05

PAncho


People also ask

How do you handle null in GSON?

We can force Gson to serialize null values via the GsonBuilder class. We need to call the serializeNulls() method on the GsonBuilder instance before creating the Gson object. Once serializeNulls() has been called the Gson instance created by the GsonBuilder can include null fields in the serialized JSON.

What does GSON toJson do?

Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.


1 Answers

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.

like image 194
Vikas Madhusudana Avatar answered Sep 20 '22 05:09

Vikas Madhusudana