如何使用 moshi 解析具有在编译时未知的键的 json 结构:
"foo": {
"name": "hello",
"bar": {
"unknownKey1": {
"a": "1"
}
},
"unknownKey2": {
"b": "2"
},
"unknownKeyX": {
"c": "X"
}
},
"properties": {...}
}
我尝试使用@FromJson
适配器,JSONObject
但日志只是说 json 是空的{}
(我期望的地方{"unknownKey1": { ... etc ...}
)
class Foo {
@Json(name = "name")
String name;
@Json(name = "bar")
Bar bar;
static class Bar {
}
}
class BarAdapter {
@FromJson
Bar fromJson(JSONObject json) {
Log.d("xxx", "got " + json.toString());
return new Bar();
}
}
一旦我可以在 json inside 栏中,我可以手动迭代它以添加到列表或其他东西(因为我不知道会有多少项目)。
像这样使用它:
Moshi moshi = new Moshi.Builder()
.add(new BarAdapter())
.add(new LinkedHashMapConverter())
.build();
我还必须添加LinkedHashMapConverter
以安抚moshi 神,但是向其中添加日志,它的方法永远不会被调用(这可能是我真正的 json 的一个单独问题)。
有任何想法吗?