我正在和Kotlin一起使用Moshi。根据{{3}},自定义TypeAdapter可能会这样:
SELECT v.*, t.type
FROM t CROSS APPLY
(SELECT MAX(CASE WHEN seqnum = 1 THEN n END) as n1,
MAX(CASE WHEN seqnum = 2 THEN n END) as n2,
MAX(CASE WHEN seqnum = 3 THEN n END) as n3,
MAX(CASE WHEN seqnum = 4 THEN n END) as n4,
MAX(CASE WHEN seqnum = 5 THEN n END) as n5,
MAX(CASE WHEN seqnum = 6 THEN n END) as n6
FROM (SELECT v.n,
ROW_NUMBER() OVER (ORDER BY n) as seqnum
FROM (VALUES (t.n1), (t.n2), (t.n3), (t.n4), (t.n5), (t.n6)
) v(n)
) v
) v;
它接收一个对象或字符串,然后转换为另一个。但是我做了一个这样的适配器:
class CardAdapter {
@ToJson String toJson(Card card) {
return card.rank + card.suit.name().substring(0, 1);
}
@FromJson Card fromJson(String card) {
return //...
}
}
原始JSON格式:
class ConfigAdapter{
@ToJson
fun toJson(writer: JsonWriter, value: WfBaseConfig?) {
val moshi = Moshi.Builder().build()
when (value) {
is BoolConfig -> moshi.adapter(BoolConfig::class.java).toJson(writer, value)
// Other types ...
else -> throw
IllegalArgumentException("Unknown wf config type: ${value::class.java.simpleName}")
}
}
@FromJson
fun fromJson(reader: JsonReader): BaseConfig? {
var type = ""
val copy = reader.peekJson()
copy.readObject {
when (copy.selectName(JsonReader.Options.of("type"))) {
0 -> type = copy.nextString()
else -> copy.skipNameAndValue()
}
}
val moshi = Moshi.Builder().build()
return when (type) {
"boole" -> moshi.adapter(BoolConfig::class.java).fromJson(reader)
// Other operations...
else -> {
e("Unknown config type: $type")
null
}
}
}
private fun JsonReader.skipNameAndValue() {
skipName()
skipValue()
}
}
说明:每个对象的格式由[
{
"id": "show_weather",
"type": "boole",
"title_en": "Show Weather",
"def": false
},
{
"id": "text_size",
"type": "list",
"title_en": "Text Size",
"item_type": "text",
"def": 1,
"data": [{
"id": 0,
"title_en": "Large",
},
{
"id": 1,
"title_en": "Middle",
},
{
"id": 2,
"title_en": "Small",
}
]
}
]
确定,如果为type
,则list
的格式将由data
确定。
使用它:
item_type
它也很好用。解析的逻辑并不重要。我只是无法确定我们可以在val listType = Types.newParameterizedType(List::class.java, BaseConfig::class.java)
val moshi = Moshi.Builder().add(ConfigAdapter()).build()
return moshi.adapter<List<BaseConfig>>(listType).fromJson(conf)
或toJson()
中使用什么类型或参数。我找不到与此有关的任何文档。
顺便说一下,这些参数是由
fromJson()
生成的,但是我最后删除了'extent',因为它会导致JsonAdapter<T>
警告logcat输出。对于何时扩展Unable to resolve Lcom/squareup/moshi/JsonAdapter; annotation class 7823
类或仅扩展JsonAdapter
/@ToJson
注释,我也感到困惑。
任何解释将不胜感激。