【问题标题】:Moshi - Parse unknown json keysMoshi - 解析未知的 json 键
【发布时间】: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


    【解决方案1】:

    使用地图。

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

    如果您也不知道地图值的类型,则不能使用 Object。

    【讨论】:

    • 你可以使用Object吗?
    • 对象是特殊的。它会根据 JSON 的内容转换为 Map、List、Double、String 或 Boolean。
    • @JesseWilson 这似乎根本不适用于 kotlin 和 Retrofit2。任何线索为什么?什么是巴兹?
    猜你喜欢
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 2020-02-10
    相关资源
    最近更新 更多