Moshi - Parse unknown json keys

一个人想着一个人 提交于 2021-01-27 05:13:09

问题


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": {...}
}

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();
    }
}

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).

Using it like this:

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

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).

any ideas?


回答1:


Use a Map.

@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.



来源:https://stackoverflow.com/questions/37060032/moshi-parse-unknown-json-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!