Raviprakash
Raviprakash

Reputation: 2440

JSON to Java conversion using GSON with generic member

I need to call REST Webservice which accepts json and gives json response. In the json structure there is request header which is common to all APIs request and response. In the below e.g you find that request header is common and only field that changes is loginResult and loginResponse.

I will generate class POJO classes for each request and response. One way is adding both loginRequest and loginResponse both fields to JSONBody class. I have many more API calls and the JSONBody will have many more unwanted members.

My Question is :
How to encapsulate the variable field (loginResult , loginResponse etc) and convey the same to gson.

I tried using generics

 public class JSONBody<T> {
        private RequestHeader requestHeader;
        private T loginRequest;
        private Map<String, Object> additionalProperties = new HashMap<String, Object>();
} 

...


 Type fooType = new TypeToken<JSONBody<LoginRequest>>() {
              }.getType();

              JSONBody<LoginRequest> body1 = gson.fromJson(body,fooType);

But what I didn't get how can I convey gson to use LoginRequest or LoginResponse class should be used in conversion?

Sample Request:

 "jsonBody": {
        "requestHeader": {
          "serviceID": "",
          "serviceCode": "LOGIN",
          "deviceDetails": {
            "deviceOS": "Win32",
            "deviceOSVersion": "Win32",
            "uuid": "A12ED324"
          }
        },
        "loginRequest": {
          "username": "asd",
          "pwd": "123"
        }

Sample Response:

 "jsonBody": {
        "requestHeader": {
          "serviceID": "",
          "serviceCode": "LOGIN",
          "deviceDetails": {
            "deviceOS": "Win32",
            "deviceOSVersion": "Win32",
            "uuid": "A12ED324"
          }
        },
        "loginResponse": {
          "responseCode": "200",
          "responseString": "Success"
        }

Upvotes: 0

Views: 275

Answers (1)

Rohit Rai
Rohit Rai

Reputation: 286

You can simply tell gson which class to use for conversion in following manner:

Gson gson = new Gson();
LoginResponse response = gson.fromJson(RESPONSE_STRING, LoginResponse .class);

where RESPONSE_STRING is string representation of your server response which can be byte[].

Upvotes: 2

Related Questions