我是 Ktor 的新手,我来自 Retrofit 背景,我想映射这个 json:
{
"key1": "value1",
"key2": "value2",
...
}
进入(实际上我不需要将json本身映射为反序列化版本):
[
{"key1": "value1"},
{"key2": "value2"},
...
]
@Serializable
data class MyObject(
val member1: String,
val member2: String
)
我在官方文档中看到的样本并没有太大帮助,所以我尝试了类似的方法:
@InternalSerializationApi
object CustomDeserializer : DeserializationStrategy<List<MyObject>> {
@ExperimentalSerializationApi
override val descriptor = buildSerialDescriptor("MyObject", PolymorphicKind.OPEN){
element("key", String.serializer().descriptor)
element("value", String.serializer().descriptor)
}
@ExperimentalSerializationApi
override fun deserialize(decoder: Decoder): List<MyObject> = decoder.decodeStructure(descriptor) {
val result = ArrayList<MyObject>()
loop@ while (true) {
val index = decodeElementIndex(descriptor)
if (index == DECODE_DONE) {
break@loop
} else if (index > 1) {
throw SerializationException("Unexpected index $index")
} else {
result.add(MyObject(decodeStringElement(descriptor, index = 0), decodeStringElement(descriptor, index = 1)))
}
}
return result
}
}
问题:
- 我是在正确的道路上,还是有更好的方法来实现它?
- 如何将此添加到我的客户?(可能仅针对特定请求)
ps:这就是我使用 Gson 的方式(忽略这是在 Java 中的事实):
public class MyObjectConverterFactory implements JsonDeserializer<List<MyObject>> {
@Override
public List<MyObject> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
List<MyObject> res = new ArrayList<>();
if (json != null && json.getAsJsonObject() != null) {
JsonObject object = json.getAsJsonObject();
Set<String> keys = object.keySet();
for (String key : keys) {
res.add(new MyObject(key, object.get(key).getAsString()));
}
}
return res;
}
}