8

如何使用 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 的一个单独问题)。

有任何想法吗?

4

1 回答 1

8

使用地图。

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

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

于 2016-05-06T02:02:49.690 回答