Blu*_*ell 6 java parsing json gson moshi
我如何用moshi解析一个json结构,它具有在编译时未知的键:
"foo": {
"name": "hello",
"bar": {
"unknownKey1": {
"a": "1"
}
},
"unknownKey2": {
"b": "2"
},
"unknownKeyX": {
"c": "X"
}
},
"properties": {...}
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用@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();
}
}
Run Code Online (Sandbox Code Playgroud)
一旦我可以进入json内部栏,我可以手动迭代它以添加到列表或其他东西(因为我不知道将有多少项).
像这样使用它:
Moshi moshi = new Moshi.Builder()
.add(new BarAdapter())
.add(new LinkedHashMapConverter())
.build();
Run Code Online (Sandbox Code Playgroud)
我还必须添加LinkedHashMapConverter
以安抚moshi众神,但添加日志,它的方法永远不会被调用(这可能是我真正的json的一个单独的问题).
有任何想法吗?
使用地图.
@FromJson
Bar fromJson(Map<String, Baz> json) {
Log.d("xxx", "got " + json.toString());
return new Bar();
}
Run Code Online (Sandbox Code Playgroud)
如果您还不知道地图值的类型,则无法使用Object.