简体   繁体   English

改造Json对Gson Android Kotlin / Java的动态响应

[英]Dynamic Response from Retrofit Json to Gson Android Kotlin/Java

I have dynamic json format from rest API like this : 我有来自其余API的动态json格式,如下所示:

{
    "data": {
        "response_code": "success",
        "value": {
            "Table": [
                {
                    "id": 5,
                    "username": "blahblah",
                    "password": "blahblah",
                    "role": 2,
                    "email": "blah@tes.com",
                    "tanggal_buat": "2019-01-01T00:00:00"
                }
            ]
        }
    },
    "meta": {
        "http_status": 200
    }
}

Object "value" has an object array name "Table". 对象“值”的对象数组名称为“表”。 Table can contain value from my database dynamically depend on my query. 表可以包含我数据库中的值,这取决于我的查询。 So, Sometimes the json format will change for example : 因此,有时json格式会更改,例如:

{
    "data": {
        "response_code": "success",
        "value": {
            "Table": [
                {
                    "id_product": 44,
                    "product": "blahblah",
                    "lot": "blahblah",
                    "qty": 2,
                }
            ]
        }
    },
    "meta": {
        "http_status": 200
    }
}

How to accept the json value and assign to gson directly with different subclass of "Table" 如何接受json值并使用“表”的不同子类直接分配给gson

I try it in retrofit and using kotlin 我尝试翻新并使用Kotlin

override fun onResponse(call: Call<MainResp>, response: Response<MainResp>) {
                    mainResponse : MainResp = response.body()
                }

Assuming that you have the following class among others (using sth like http://www.jsonschema2pojo.org/ ): 假设您拥有以下课程(使用诸如http://www.jsonschema2pojo.org/之类的东西 ):

class Value {
    List<Table> tables;
}

The "Table" class here cannot be completely random! 这里的“ Table”类不能完全随机!
You'll need to define the possible types of "Table" eg Table1, Table2... TableN. 您需要定义“表格”的可能类型,例如,表格1,表格2 ...表格N。

Now you can update Value class with a generic type T instead of Table and write your custom type adapter: 现在,您可以使用通用类型T代替Table更新Value类,并编写自定义类型适配器:

class Value {
    List<T> tables;
} 

One of the tutorials on how to write your own type adapter is here . 这里是有关如何编写自己的类型适配器的教程之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM