Moshi Determine if JSON is array or single object

后端 未结 2 1549
孤街浪徒
孤街浪徒 2021-01-18 07:16

Is there a way to setup a Moshi adapter to automatically create a single Object or List based on the JSON response? Curr
2条回答
  •  轮回少年
    2021-01-18 07:23

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

提交回复
热议问题