2

I am trying to parse JSON from server. I have Pojo Model but the server JSON is sending boolean as True, False instead of true,false. Is it possible to map this using custom GSONbuilder etc.

Here is my class

public class User {

      private String id;
      private String name;
      private boolean isOnline;

}

Here is my JSON from server

{
  "user": {
    "id": 1,
    "name": "Abc",
    "isOnline": True
  }
}

User user = new Gson().fromJSON(json,User.class);

  • possible duplicate of [GSON False uppercase](http://stackoverflow.com/questions/4722773/gson-false-uppercase) – Vishwanath Dec 30 '14 at 10:36
  • This question apperas to be duplicate of http://stackoverflow.com/questions/4722773/gson-false-uppercase . Please check if you need the same thing. – Vishwanath Dec 30 '14 at 10:36

3 Answers3

1

You are doing it wrong. If your json string is the way you have given they you need to create another model class with user object and give it's class while serializing. Or do as I have done in following code. True or true does not matter.

public class HelloWorld {

    public static void main(String args[]) {

        String json = "{'id': 1,'name': 'Abc','isOnline': True}";
        User user = new Gson().fromJson(json, User.class);
        System.out.println(user);
    }

}

class User {

    private String id;
    private String name;
    private boolean isOnline;

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", isOnline=" + isOnline
                + "]";
    }
}

and output is

User [id=1, name=Abc, isOnline=true]

Recreating the Model state (Desererialization) is done via reflection and case sensitive boolean string is taken care of. You can check the same by

System.out.println(Boolean.parseBoolean("true"));
System.out.println(Boolean.parseBoolean("True"));
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0

Assuming you are using Google Gson here, your object creation is incorrect; you would need your JSON to look like this for it to work:

{
   "id": 1,
   "name": "Abc",
   "isOnline": True
}

To unpack the response as given, define another class like this:

public class JsonResponse {
    private User user;
}

... and unpack with:

JsonResponse user = new Gson().fromJSON(json, JsonResponse.class);

... which should give you a response with a correctly populated User in it.

BarrySW19
  • 3,759
  • 12
  • 26
  • Hmm, marked down without comment despite being basically the same as the accepted answer. There's some very strange people out there. – BarrySW19 Dec 30 '14 at 11:04
-1

You need to write a custom deserializer. Here are some examples:

Community
  • 1
  • 1
Baderous
  • 1,069
  • 1
  • 11
  • 32