通过retrofit2和Rx获得api的回复

时间:2018-05-28 05:35:00

标签: android rx-java retrofit2

我使用Retrofit和Rx发送请求并从API获取JSON。 一切都很好,但是当我想访问JSON数组时,它无法正常工作。

public class Device {
private boolean current;
private String uid;

public boolean isCurrent() {
    return current;
}

public void setCurrent(boolean current) {
    this.current = current;
}

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}
}
public class DeviceResult {
private ArrayList<Device> devices;

public ArrayList<Device> getDevices() {
    return devices;
}

public void setDevices(ArrayList<Device> devices) {
this.devices = devices; } }

您可以看到DeviceResult类有一个名为devices

的ArrayList
public interface TokenApi {
    @GET("devices")
    Observable<Response<DeviceResult>> getDeviceId(@Header("Authorization") 
    String token);
    }

deviceResults.isSuccessful()是真的,我在Okhttp日志中看到了我的回应,但deviceResults.body()并不是我所期待的。

 RetrofitHelper retrofitHelper = new RetrofitHelper("http://172.16.16.16");
    TokenApi tokenApi = retrofitHelper.getService(TokenApi.class);
    rx.Observable<Response<DeviceResult>> listObservable = tokenApi.getDeviceId("Bearer" + " " + getToken());
    listObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(deviceResults -> {
        if (deviceResults.isSuccessful()) {
// isSuccessful is true
// the problem is body tell me some dumy thing
            Log.i("Devices_body", deviceResults.body().toString());
            Log.i("Devices_message", deviceResults.message());
        }

    }, throwable -> Log.i("Error get devices", throwable.toString()));

我的JSON数组

{
"devices": [
    {
        "agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36",
        "browser": "Chrome",
        "current": false,
        "deviceType": "Desktop",
        "id": 9848,
        "ip": "172.16.106.40",
        "lastAccessTime": 1527337813000,
        "os": "Win10",
        "osVersion": "10.0",
        "uid": "f3fcf0845df6e83cd150e86aadc37206"
    },
    {
        "agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0",
        "browser": "Firefox",
        "browserVersion": "59",
        "current": true,
        "deviceType": "Desktop",
        "id": 9828,
        "ip": "172.16.106.44",
        "lastAccessTime": 1527066972000,
        "os": "Win10",
        "osVersion": "10.0",
        "uid": "3d943476a879dcf609f79a5ec736bedc"
    },
}
  

问题deviceResults.body().toString()没有得到我   JSON但是我看到了Okhttp日志,请求的响应是   工作得很好!

2 个答案:

答案 0 :(得分:0)

关键是我刚看到调试器,并了解响应(deviceResults.body())让我ArrayList<Device>并且我不需要将其解析为JSONObject

答案 1 :(得分:0)

您必须使用此链接为您的回复创建POJO类。 之后尝试应用GsonConvertorFactory

dependencies {  
// Retrofit & OkHttp
compile 'com.squareup.retrofit2:retrofit:2.3.0'

// JSON Converter
compile 'com.squareup.retrofit2:converter-gson:2.3.0'

}

然后尝试将Response Array或Object转换为JSON。