翻新,将json转换为动态json,空机身

时间:2019-07-15 17:05:47

标签: android json parsing gson retrofit2

我正在使用Retrofit2,我需要调用API以获得信息。 API提供给我的JSON具有动态字段,这些字段根据参数值而变化。请注意,我可以有任意数量的参数。我尝试解析动态字段,但drom api的响应为空。

https://ibb.co/HnXFD2M

Json例如参数{1,2}

{
   "data":{
      "1":{   
          "logo":"https://s2.coinmarketcap.com/static/img/coins/64x64/1.png",
          "id":1,
          "name":"Bitcoin",
          "symbol":"BTC",
          "description":"Bitcoin (BTC) is...",
          "date_added":"2013-04-28T00:00:00.000Z",
          "platform":null,
          "category":"coin"
      }
   },
   "2":{
      "logo":"https://s2.coinmarketcap.com/static/img/coins/64x64/2.png",
      "id":2,
      "name":"Litecoin",
      "symbol":"LTC",
      "description":"Litecoin(LTC) is...",
      "date_added":"2014-03-28T00:00:00.111Z",
      "platform":null,
      "category":"coin"
   }
}

我的课程:

public class CurrencyResponse {

    @SerializedName("data")
    @Expose
    private Data data;

    public Data getData() {
        return data;
    }

    public void setData(Data data) {
        this.data = data;
    }
}

public class Data {
    public HashMap<String, CurrencyInfo> currencyInfo;

    public Data() {
    this.currencyInfo = new HashMap<>();
    }

}

public class CurrencyInfo {

    @SerializedName("logo")
    @Expose
    private String logo;
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("symbol")
    @Expose
    private String symbol;
    @SerializedName("description")
    @Expose
    private String description;
}

Api类:

public class ApiConstants {
    public static String APP_KEY="xxxxxxxxxxxxxxxxxxxxxxxxxx";
    public static String BASE_URL = "https://pro-api.coinmarketcap.com/";
    public static final String CRYPTOCURRENCYINFO="v1/cryptocurrency/info";
}

接口:

public interface CurrencyService {
    @GET(ApiConstants.CRYPTOCURRENCYINFO)
    Call<CurrencyResponse> getCurrencyById(@Header("X-CMC_PRO_API_KEY") 
String appkey,
                                           @Query("id") int into);
}

解析器:

public class DataInfoParser implements JsonDeserializer<Data> {
    @Override
    public Data deserialize(JsonElement json,
                            Type typeOfT,
                            JsonDeserializationContext context) throws 
JsonParseException {
        Data result = new Data();
        try {
            final HashMap<String, CurrencyInfo> map = 
readServiceUrlMap(json.getAsJsonObject());
            if (map != null) {
                result.currencyInfo = map;
            }
        } catch (JsonSyntaxException ex) {
            return null;
        }
        return result;
    }

    private HashMap<String, CurrencyInfo> readServiceUrlMap(final JsonObject 
jsonObject) throws JsonSyntaxException {
        if (jsonObject == null) {
            return null;
        }
        Gson gson = new Gson();

        HashMap<String, CurrencyInfo> products = new HashMap<>();

        for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {

            String key = entry.getKey();
            CurrencyInfo info = gson.fromJson(entry.getValue(), 
CurrencyInfo.class);
            products.put(key, info);
        }
        return products;
    }
}

改造:

public class RetrofitClient {
    private static RetrofitClient instance = null;
    private Retrofit retrofit;
    private OkHttpClient client;
    private CurrencyService currencyService;
    private TestService testService;

    private RetrofitClient() {

        GsonBuilder gsonBuilder=new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Data.class,new DataInfoParser());
        OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
        client = okHttpBuilder.build();
        retrofit = new Retrofit.Builder().baseUrl(ApiConstants.BASE_URL)

.addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))
                .client(client)
                .build();

        currencyService = retrofit.create(CurrencyService.class);
        testService = retrofit.create(TestService.class);
    }

    public static RetrofitClient getInstance() {
        if (instance == null) {
            instance = new RetrofitClient();
        }
        return instance;
    }

    public CurrencyService getCurrencyService() { return currencyService; 
}

    public TestService getTestService() { return testService; }
}

0 个答案:

没有答案