1

I am having below 2 JSON, one for login and another one for order

{
          "head": {
            "requestCode": "code"
          },
          "body": {
            "reqId": "xyz",
            "userName": "xyz",
            "passwd": "xyz",
          }
        }
        
        {
          "head": {
            "requestCode": "code"
          },
          "body": {
            "reqId": "xyz",
            "orderId": "xyz"
          }
        }

I am trying to write java pojo where the head and refId of body are common for each json but other content of body.

something like the below pojo. Now problem is GSon cannot parse and build objects based on nested parameterized types. Is there any better way to implement it? Not JSON structure will not change.

POJO

public class Base<T extends Body> {

@SerializedName("head")
@Expose
public Head head;
@SerializedName("body")
@Expose
private T body;
}

public class Body {
@SerializedName("clientCode")
@Expose
private String clientCode;
}

public class Head {
@SerializedName("requestCode")
@Expose
public String requestCode;
}

public class Login extends Body {
@SerializedName("userName")
@Expose
public String userName;
@SerializedName("passwd")
@Expose
public String passed;
}

public class Order extends Body {
@SerializedName("orderId")
@Expose
String orderId;
}
MDK
  • 499
  • 3
  • 14
  • Do you know in advance if the response is `Login` or `Order`? Otherwise the answers to https://stackoverflow.com/q/15736654 might be helpful. – Marcono1234 Jul 24 '22 at 20:57
  • Yes, I know that receiving JSON structure will be the same, even in case of error. {head:{...},body:{..}} . underlying body data will differ. – Pankaj Patel Jul 25 '22 at 03:48
  • What I meant was: When receiving a request, do you know before calling Gson (1) "This JSON data is a `Login` request" and "This JSON data is an `Order` request", or do you just know that (2) "This JSON data is either a `Login` or `Order` request and Gson has to figure out the type"? In the latter case and if you cannot modify the JSON data structure, then maybe [Jackson's deduction-based polymorphism feature](https://cowtowncoder.medium.com/jackson-2-12-most-wanted-1-5-deduction-based-polymorphism-c7fb51db7818) is better suited for this. – Marcono1234 Jul 25 '22 at 12:31
  • Yes, these are responses from services, different responses for different requests, so yes receiving json is well known during receiving. – Pankaj Patel Jul 25 '22 at 17:42

1 Answers1

1

You could either introduce two new subclasses of Base which you use for deserialization, for example:

  • class LoginRequest extends Base<Login> { }
  • class OrderRequest extends Base<Order> { }

Or you can use Gson's TypeToken class to deserialize a parameterized Base type. See also the corresponding section in the user guide. For example:

Type loginType = new TypeToken<Base<Login>>() {}.getType();
Base<Login> loginRequest = gson.fromJson(..., loginType);
Marcono1234
  • 5,856
  • 1
  • 25
  • 43