【问题标题】:How to parse dynamic JSON with Retrofit 2 (+Nested objects)如何使用 Retrofit 2(+嵌套对象)解析动态 JSON
【发布时间】:2018-05-31 20:51:13
【问题描述】:

我正在尝试解析看起来像这样的 JSON 响应。

{
    "Cryptsy": {
        "AMC": [
            "BTC"
        ],
        "CIRC": [
            "BTC"
        ],
        "SYNC": [
            "BTC"
        ]
    },
    "Bitstamp": {
        "EUR": [
            "USD"
        ],
        "ETH": [
            "USD",
            "EUR"
        ],
        "XRP": [
            "USD",
            "EUR",
            "BTC"
        ]
    },
    // ...
    // More objects...
    // ...
}

如您所见,这个具有动态键,每个值也是具有动态键的对象。我尝试使用 retrofit2 和 GsonConverter 解析它,但它会导致异常

W/System.err: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2 path $

我认为这是因为 JSON 是嵌套的,并且所有对象都没有任何固定键。

这是我的代码。

PairListResponse.java

// This is the GSON model class

class PairListResponse {

    private Map<String, Map<String, String[]>> exchangePairs;

    PairListResponse() {
    }

    Map<String, Map<String, String[]>> getExchangePairs() {
        return exchangePairs;
    }

    void setExchangePairs(Map<String, Map<String, String[]>> exchangePairs) {
        this.exchangePairs = exchangePairs;
    }

    Map<String, String[]> getTradingPairs(String fromSymbol) {
        return exchangePairs.get(fromSymbol);
    }
}

PairListDeserializer.java

public class PairListDeserializer implements JsonDeserializer<PairListResponse> {

    private static final String TAG = PairListDeserializer.class.getSimpleName();

    @Override
    public PairListResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        final JsonObject jsonObject = json.getAsJsonObject();
        final Map<String, Map<String, String[]>> exchangePairs = readPairMap(jsonObject);
        PairListResponse result = new PairListResponse();
        result.setExchangePairs(exchangePairs);
        return result;
    }

    @Nullable
    private Map<String, Map<String, String[]>> readPairMap(@NonNull final JsonObject jsonObject) {
        // Initializing Hashmap for the outer object
        final Map<String, Map<String, String[]>> result = new HashMap<>();

        for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            String exchange = entry.getKey();
            String fromSymbol;
            String[] toSymbols;
            JsonObject fsymbolObj = entry.getValue().getAsJsonObject();

        // Initializing Hashmap for inner objects
            final Map<String, String[]> pairsPerCoin = new HashMap<>();

            for (Map.Entry<String, JsonElement> inner_entry : fsymbolObj.entrySet()) {
                fromSymbol = inner_entry.getKey();
                toSymbols = toStringArray(inner_entry.getValue().getAsJsonArray());
                pairsPerCoin.put(fromSymbol, toSymbols);
            }
            result.put(exchange, pairsPerCoin);
        }
        return result;
    }

    private static String[] toStringArray(JsonArray array) {
        if (array == null) return null;
        String[] arr = new String[array.size()];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = array.get(i).toString();
        }
        return arr;
    }
}

提前致谢!

【问题讨论】:

    标签: java android json gson retrofit


    【解决方案1】:

    对不起,我犯了一个最愚蠢的错误! 在我的改造 API 调用中,我忘记设置正确的模型类名称。

    public interface TradingPairAPICall {
        @GET("exchanges")
        Call<String> getAllPairList();
    }
    

    其实应该是的

    Call<PairListResponse> getAllPairList();
    

    我改变了它,它成功地工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-12
      • 2021-02-03
      • 2016-01-01
      • 1970-01-01
      • 2018-07-12
      • 2019-07-30
      • 1970-01-01
      相关资源
      最近更新 更多