Moshi - Parse unknown json keys

How can I parse a json structure with moshi 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 an adapter @FromJsonfor JSONObject, but the logs just say 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();
    }
}

As soon as I can get into the json inner panel, I can manually iterate through it to add to the list or something like that (since I don't know how many elements there will be).

Using it as follows:

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

I also had to add LinkedHashMapConverterto reassure the gods of the mosh, but adding logs to it, its methods are never called (this may be a separate issue with my real json).

any ideas?

+4
1

.

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

, Object.

+3

All Articles