【发布时间】:2016-08-31 19:09:31
【问题描述】:
我如何用 moshi 解析一个 json 结构,它的键在编译时是未知的:
"foo": {
"name": "hello",
"bar": {
"unknownKey1": {
"a": "1"
}
},
"unknownKey2": {
"b": "2"
},
"unknownKeyX": {
"c": "X"
}
},
"properties": {...}
}
我尝试为JSONObject 使用@FromJson 适配器,但日志只是说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 bar,我可以手动对其进行迭代以添加到列表或其他内容中(因为我不知道会有多少项)。
像这样使用它:
Moshi moshi = new Moshi.Builder()
.add(new BarAdapter())
.add(new LinkedHashMapConverter())
.build();
我还必须添加LinkedHashMapConverter 来安抚moshi 众神,但是向其中添加日志,它的方法永远不会被调用(这可能是我真正的json 的一个单独问题)。
有什么想法吗?
【问题讨论】:
标签: java json parsing gson moshi