Handle JSON response with multiple type of the same name

主宰稳场 提交于 2020-01-06 04:42:18

问题


The JSON response is :

{
    "success": false,
    "errorMessages": [
        "You have to select a maximum load of <span style='color:red;'>0</span> Credit/Course but you have selected <span style='color:red;'>3</span> Credit/Course --- [R060]",
        "You can register courses as a full study with a load limit between <span style='color:red;'>12</span> and <span style='color:red;'>18</span> Credit/Course, but you have selected <span style='color:red;'>9</span> Credit/Course --- [R062]"
    ],
    "isConflict": 0
}

but when isConflict == 1 the response is:

{
    "ignoreConflictValue": "W",
    "isConflict": 1,
    "conflict": [
        {
            "EXAM_DATE": "01/01/2019",
            "START_TIME": "08:00 AM",
            "END_TIME": "09:30 AM",
            "COURSE_NAME_SL": "مقاومة مواد,تقنيات الحفر البحري",
            "COURSE_NAME_PL": "STRENGTH OF MATERIALS,OFFSHORE TECHNOLOGY",
            "COURSES_COUNT": "2",
            "ACTIVE": "A"
        }
    ],
    "success": false
}

The logic of this API is :

  • when isConflict == 1 the success property is type of Integer with values 1 and 0.
  • Otherwise the success property is type of Boolean with values true and false

My question is how to define the POJO class for this situation.

I tried to make two fields with the same name with @Nullable for both but Gson complains that the POJO has duplicate fields.


回答1:


In Kotlin you can do the following:

Define "ApiResponse" class with generics like below:

class ApiResponse(@SerializedName("success") val success : Any,
                  @SerializedName("errorMessages") val errorMessages : Array<Any>,
                  @SerializedName("isConflict")
                  val isConflict : Integer)

Then, in your activity, use Gson to convert the response with

 var responseOne = Gson().fromJson(textConflictOneResponse, ApiResponse::class.java)
        var responseZero = Gson().fromJson(textConflictZeroResponse, ApiResponse::class.java)

Then you can check the type of the response by doing:

if (responseOne.success is Boolean){
            Log.v(TAG,"Boolean")
        } else{
            Log.v(TAG,"not boolean")
        }


来源:https://stackoverflow.com/questions/53611583/handle-json-response-with-multiple-type-of-the-same-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!