处理具有相同名称的多种类型的JSON响应

时间:2018-12-04 11:07:36

标签: android retrofit2 gson

JSON响应为:

{
    "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
}

但是当isConflict == 1时,响应为:

{
    "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
}

此API的逻辑是:

  • isConflict == 1的成功属性是类型为Integer且值为1和0时。
  • 否则,成功属性是类型为Boolean和值为true的{​​{1}}

我的问题是如何针对这种情况定义POJO类。

我试图用false为两个字段创建相同的名称,但是@Nullable抱怨POJO字段重复。

1 个答案:

答案 0 :(得分:1)

在Kotlin中,您可以执行以下操作:

使用如下通用名称定义“ ApiResponse”类:

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

然后,在您的活动中,使用Gson将响应转换为

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

然后您可以通过以下操作检查响应的类型:

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