How to handle Dynamic JSON in Retrofit?

后端 未结 10 2252
余生分开走
余生分开走 2020-11-22 16:23

I am using the retrofit efficient networking library, but I am unable to handle Dynamic JSON which contains single prefix responseMessage which changes to

10条回答
  •  逝去的感伤
    2020-11-22 16:55

    I too ran of this issue. but i am not sure if this was your case , (i am using Retrofit2)

    on my case i need to handle error, and success messages.

    On Success

    {
    "call_id": 1,
    "status": "SUCCESS",
    "status_code": "SUCCESS",
    "result": {
        "data1": {
            "id": "RFP2UjW7p8ggpMXzYO9tRg==",
            "name": "abcdef",
            "mobile_no": "96655222",
            "email": ""
        },
        "data2": [
            {
                "no": "12345"
            },
            {
                "no": "45632"
            }
        ]
    }
    }
    

    On Error,

    {
    "call_id": 1,
    "status": "FAILED",
    "status_code": "NO_RECORDS",
    "error": {
        "error_title": "xxx",
        "error_message": "details not found"
    }
    }
    

    for this i just created another POJO Error,

    public class ValidateUserResponse {
    @SerializedName("call_id")
    public String callId;
    @SerializedName("status")
    public String status;
    @SerializedName("status_code")
    public String statusCode;
    @SerializedName("result")
    public ValidateUserResult result;
    @SerializedName("error")
    public Error error;
    }
    

    Error.java

    public class Error {
    @SerializedName("error_title")
    public String errorTitle;
    @SerializedName("error_message")
    public String errorMessage;
    }
    

    ValidateUser.java

    public class ValidateUserResult {
    
    @SerializedName("auth_check")
    public String authCheck;
    @SerializedName("data1")
    public Data1 data1;
    @SerializedName("data2")
    public List data2;
    }
    

    in the above case if the result key on json contains data1,data2 then the ValidateUserResult.java get initialised. if error then the Error.java class get initialized.

提交回复
热议问题