Gson - 命名对象到数组

时间:2018-01-07 04:25:06

标签: android json gson

在来自服务器的响应中,数据被构造为命名对象。我试图找出如何将其转换为具有特定字段详细信息的数组。

来自服务器的响应示例。

{ 
    "Value_1": { "Foo": "True", "Bar": "False"},
    "Value_2": { "Foo": "False", "Bar": "False"},
    "Value_3": { "Foo": "False", "Bar": "True"}
}

服务器的首选转换结果示例。

{[
    {"Name": "Value_1", 
    "Details": [{"Name": "Foo", "Value": "True"},
    {"Name": "Bar", "Value": "False"}]},

    {"Name": "Value_2", 
    "Details": [{"Name": "Foo", "Value": "False"},
    {"Name": "Bar", "Value": "False"}]},

    {"Name": "Value_3", 
    "Details": [{"Name": "Foo", "Value": "False"},
    {"Name": "Bar", "Value": "True"}]}
]}

如何告诉gson从响应转换为首选结构?

1 个答案:

答案 0 :(得分:0)

我能够使用自定义JsonDeserializer在一个相当干净的方法中完成此任务。主要的是JsonObject.entrySet(),它为您提供了JsonObject的键/值对,因此您可以迭代它们。

首先,在构建Retrofit客户端时,添加自定义JsonDeserializer。

    gsonBuilder.registerTypeAdapter(MyModel::class.java, MyModelDeserializer())

然后像这样实现它。

class MyModelDeserializer : JsonDeserializer<MyModel> {

    override fun deserialize(json : JsonElement, typeOfT : Type?, context : JsonDeserializationContext?) : MyModel {
        val jsonObject = json.asJsonObject

        // Create a new ArrayList to store the values.
        val list = ArrayList<MyModel>()

        // Using entrySet, get each key/value pair. "Value_1: {...}"
        for (entry in jsonObject.entrySet()) {
            val valueName = entry.key // The key, which would be the name "Value_1"

            // Creating a new ArrayList to contain all the data.
            val vals = ArrayList<Pair<String, Boolean>>()

            val values = entry.value.asJsonObject

            // Using entrySet again for each value of the Object.
            for (entry in values.entrySet()) {
                vals.add(entry.key to entry.value.asBoolean)
            }

            // Create a new MyModel, with the correct name and values.
            list.add(MyModel(valueName, vals))
        }

        return MyModel(list)
    }
}