Moshi-解析未知的json键 [英] Moshi - Parse unknown json keys

查看:93
本文介绍了Moshi-解析未知的json键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用moshi解析一个json结构,该结构具有在编译时未知的键:

How can I parse with moshi a json structure that has keys that are unknown at compile time:

"foo": {
  "name": "hello",
  "bar": {
    "unknownKey1": {
      "a": "1"
      }
    },
    "unknownKey2": {
      "b": "2"
    },
    "unknownKeyX": {
      "c": "X"
    }
  },
  "properties": {...}
}

我尝试对 JSONObject 使用 @FromJson 适配器,但是日志只说json为空 {} (我希望在这里 {"unknownKey1":{...等...} )

I tried using a @FromJson adapter for JSONObject but the logs just say that the json is empty {} (where I would expect {"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里面的栏,我就可以手动对其进行迭代以添加到列表或其他内容中(因为我不知道会有多少个项目).

Once I can get at the json inside bar, I can manually iterate it to add to a list or something (since I don't know how many items there will be).

像这样使用它:

         Moshi moshi = new Moshi.Builder()
        .add(new BarAdapter())
        .add(new LinkedHashMapConverter())
        .build();

我还必须添加 LinkedHashMapConverter 来安抚moshi之神,但是向其中添加日志时,它的方法从未被调用过(这可能是我的真正json的另一个问题).

I also had to add the LinkedHashMapConverter to appease the moshi gods, but adding logs to it, its methods are never called (this might be a separate issue with my real json).

有什么想法吗?

推荐答案

使用地图.

@FromJson
Bar fromJson(Map<String, Baz> json) {
    Log.d("xxx", "got " + json.toString());
    return new Bar();
}

如果您也不知道地图值的类型,则不能使用对象.

If you also don't know the type of the map’s values you can't use Object.

这篇关于Moshi-解析未知的json键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆