10

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?

Siguza
  • 18,036
  • 6
  • 48
  • 73
PAncho
  • 241
  • 2
  • 3
  • 12
  • And what happens if you only use `Gson gson = new Gson()`? – OneCricketeer May 26 '16 at 11:34
  • if i only use Gson gson = new Gson() Infinity loop at recursive calling com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375) – PAncho May 26 '16 at 11:36
  • what `excludeFieldsWithoutExposeAnnotation` says? "only expose fields that are annotated and ignore the rest " – Braj May 26 '16 at 11:38
  • Possible duplicate of [How should I escape strings in JSON?](http://stackoverflow.com/questions/3020094/how-should-i-escape-strings-in-json) – Siguza May 26 '16 at 11:38
  • ^ i.e. single quotes are not valid JSON. – Siguza May 26 '16 at 11:39

2 Answers2

8

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.

ricardopereira
  • 10,295
  • 5
  • 60
  • 72
Vikas Madhusudana
  • 1,460
  • 1
  • 10
  • 20
-2

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);
zeroDivider
  • 982
  • 14
  • 28
Kumaresan Perumal
  • 1,805
  • 25
  • 34