javajsonparsinggsonmoshi

Moshi - Parse unknown json keys


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?


Solution

  • 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 use Object.