本文介绍了处理具有相同名称的多种类型的JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
和false
- when
isConflict == 1
the success property is type ofInteger
with values 1 and 0. - Otherwise the success property is type of
Boolean
with valuestrue
andfalse
我的问题是如何针对这种情况定义POJO类.
My question is how to define the POJO class for this situation.
我试图用@Nullable
来使两个具有相同名称的字段,但是Gson
抱怨POJO具有重复的字段.
I tried to make two fields with the same name with @Nullable
for both but Gson
complains that the POJO has duplicate fields.
推荐答案
在Kotlin中,您可以执行以下操作:
In Kotlin you can do the following:
使用如下通用名称定义"ApiResponse"类:
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)
然后,在您的活动中,使用Gson将响应转换为
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")
}
这篇关于处理具有相同名称的多种类型的JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!