Is there a way to setup a Moshi adapter
to automatically create a single Object
or List
based on the JSON response? Curr
Using @Eric's comment, I came up with the correct code below:
public static List loadFakeData(String url, Class cls){
List list = new ArrayList<>();
Moshi moshi = new Moshi.Builder().build();
try {
JsonReader reader = JsonReader.of(runHttpClient(url));
JsonReader.Token token = reader.peek();
if (token.equals(JsonReader.Token.BEGIN_ARRAY)) {
Type type = Types.newParameterizedType(List.class, cls);
JsonAdapter> adapter = moshi.adapter(type);
list = adapter.fromJson(reader);
} else if (token.equals(JsonReader.Token.BEGIN_OBJECT)){
JsonAdapter adapter = moshi.adapter(cls);
T t = adapter.fromJson(reader);
list.add(t);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}