Json Get Request с использованием модернизации не будет работать - PullRequest
0 голосов
/ 17 мая 2018

До этого API у меня были такие, и теперь мой код работал, я не могу понять, что мне нужно получить и что поместить в Map, также я не знаю, с чего начать, чтобы получить этот ответ в мое приложение.

Это API, я знаю, как работает, и у меня есть рабочий код для него: https://gyazo.com/f2eb4858c48c31c5c48765a9e7512179

Но этот API действительно трудно понять для меня. https://gyazo.com/d2bad9dbe66bf7c51b169b54a68a003a

Я действительно не знаю, что мне нужно поместить здесь в Map и как получить массив "result" (если это список массива ??)

Спасибо, ребята, это мой неработающий пример.

Datas.class

package Model.BittrexApiModel;

public class Datas {

    private Result result;

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    public Datas withDatas(Result result){
        this.result=result;
        return this;
    }
}

Вот мой результат. POJO CLASS

package Model.BittrexApiModel;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Result {

    @SerializedName("MarketName")
    @Expose
    private String marketName;
    @SerializedName("High")
    @Expose
    private Double high;
    @SerializedName("Low")
    @Expose
    private Double low;
    @SerializedName("Volume")
    @Expose
    private Double volume;
    @SerializedName("Last")
    @Expose
    private Double last;
    @SerializedName("BaseVolume")
    @Expose
    private Double baseVolume;
    @SerializedName("TimeStamp")
    @Expose
    private String timeStamp;
    @SerializedName("Bid")
    @Expose
    private Double bid;
    @SerializedName("Ask")
    @Expose
    private Double ask;
    @SerializedName("OpenBuyOrders")
    @Expose
    private Integer openBuyOrders;
    @SerializedName("OpenSellOrders")
    @Expose
    private Integer openSellOrders;
    @SerializedName("PrevDay")
    @Expose
    private Double prevDay;
    @SerializedName("Created")
    @Expose
    private String created;

    public String getMarketName() {
        return marketName;
    }

    public void setMarketName(String marketName) {
        this.marketName = marketName;
    }

    public Result withMarketName(String marketName) {
        this.marketName = marketName;
        return this;
    }

    public Double getHigh() {
        return high;
    }

    public void setHigh(Double high) {
        this.high = high;
    }

    public Result withHigh(Double high) {
        this.high = high;
        return this;
    }

    public Double getLow() {
        return low;
    }

    public void setLow(Double low) {
        this.low = low;
    }

    public Result withLow(Double low) {
        this.low = low;
        return this;
    }

    public Double getVolume() {
        return volume;
    }

    public void setVolume(Double volume) {
        this.volume = volume;
    }

    public Result withVolume(Double volume) {
        this.volume = volume;
        return this;
    }

    public Double getLast() {
        return last;
    }

    public void setLast(Double last) {
        this.last = last;
    }

    public Result withLast(Double last) {
        this.last = last;
        return this;
    }

    public Double getBaseVolume() {
        return baseVolume;
    }

    public void setBaseVolume(Double baseVolume) {
        this.baseVolume = baseVolume;
    }

    public Result withBaseVolume(Double baseVolume) {
        this.baseVolume = baseVolume;
        return this;
    }

    public String getTimeStamp() {
        return timeStamp;
    }

    public void setTimeStamp(String timeStamp) {
        this.timeStamp = timeStamp;
    }

    public Result withTimeStamp(String timeStamp) {
        this.timeStamp = timeStamp;
        return this;
    }

    public Double getBid() {
        return bid;
    }

    public void setBid(Double bid) {
        this.bid = bid;
    }

    public Result withBid(Double bid) {
        this.bid = bid;
        return this;
    }

    public Double getAsk() {
        return ask;
    }

    public void setAsk(Double ask) {
        this.ask = ask;
    }

    public Result withAsk(Double ask) {
        this.ask = ask;
        return this;
    }

    public Integer getOpenBuyOrders() {
        return openBuyOrders;
    }

    public void setOpenBuyOrders(Integer openBuyOrders) {
        this.openBuyOrders = openBuyOrders;
    }

    public Result withOpenBuyOrders(Integer openBuyOrders) {
        this.openBuyOrders = openBuyOrders;
        return this;
    }

    public Integer getOpenSellOrders() {
        return openSellOrders;
    }

    public void setOpenSellOrders(Integer openSellOrders) {
        this.openSellOrders = openSellOrders;
    }

    public Result withOpenSellOrders(Integer openSellOrders) {
        this.openSellOrders = openSellOrders;
        return this;
    }

    public Double getPrevDay() {
        return prevDay;
    }

    public void setPrevDay(Double prevDay) {
        this.prevDay = prevDay;
    }

    public Result withPrevDay(Double prevDay) {
        this.prevDay = prevDay;
        return this;
    }

    public String getCreated() {
        return created;
    }

    public void setCreated(String created) {
        this.created = created;
    }

    public Result withCreated(String created) {
        this.created = created;
        return this;
    }

}

А вот мой BittrexResponse.class (я думаю, что этот не работает.)

package Model.BittrexApiModel;

import java.util.Map;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class BittrexResponse {

    @SerializedName("success")
    @Expose
    private Boolean success;
    @SerializedName("message")
    @Expose
    private String message;
    @SerializedName("result")
    @Expose
    private Map<String, Result> datas;


    public Map<String,Result> getDatas(){
        return datas;
    }

    public void setDatas(Map<String,Result> datas){
        this.datas=datas;
    }

    //private List<Result> result = new ArrayList<>();

    //This is first original JSONSCHEMA2POJO - SAVING RESPONSE DON't WORK
   // private List<Result> result = new ArrayList<Result>();

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public BittrexResponse withSuccess(Boolean success) {
        this.success = success;
        return this;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public BittrexResponse withMessage(String message) {
        this.message = message;
        return this;
    }

ApiClient.class (работает, проверено на предыдущих примерах)

package Model.CoinMarketCapApiModel;

import com.test.retrofit.CryptoCyber.Settings;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {

    public static final String BASE_URL = Settings.getBase_url();
    private static Retrofit retrofit = null;


    public static Retrofit getClient() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();



            retrofit = new Retrofit.Builder()
                    .client(client)
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

        return retrofit;
    }
}

Я надеюсь, что кто-нибудь поможет мне выяснить, почему я не знаю, получить данные и сохранить их на карту ...

P.s. вот ссылка на API НАЖМИТЕ ЗДЕСЬ

1 Ответ

0 голосов
/ 18 мая 2018

Вот один из возможных способов разработки ваших классов для правильного анализа ответа.

ApiResponse

public class ApiResponse {
    private boolean success;

    private String message;

    @SerializedName("result")
    private List<Market> markets;

    // Other fields + getters&setters
    ...
}

Рынок

public class Market {

    @SerializedName("MarketName")
    private String marketName;

    @SerializedName("High")
    private double high;

    @SerializedName("Low")
    private double low;

    @SerializedName("Volume")
    private double volume;

    // Other fields + getters&setters
    ...
}

Главная

public class Main {

    public static void main(String[] args) throws IOException {

        Retrofit retrofit = createRetrofit();

        Api api = retrofit.create(Api.class);
        retrofit2.Response<ApiResponse> response = api.getMarketSummaries().execute();
        if (!response.isSuccessful()) {
            // Handle error case
        } else {
            ApiResponse marketApiResponse = response.body();
            System.out.println(marketApiResponse);
        }
    }

    private static Retrofit createRetrofit() {
        return new Retrofit.Builder()
                .baseUrl("https://bittrex.com/api/v1.1/public/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
}

Будет напечатано что-то вроде этого (для краткости сообщается только о первом элементе списка):

ApiResponse{success=true, message='', markets=[Market{marketName='BTC-2GIVE', high=1.1E-6, low=9.7E-7, volume=3499023.70109898}, 
...