2017-02-23 28 views
0

在這下面的代碼我使用RetroFit2爲對象發佈到端點:http://localhost:3000/insert:改造響應參數之後的後

Call<DeviceModel> deviceModelCall = api.createDevice(device); 
deviceModelCall.enqueue(new Callback<DeviceModel>() { 
    @Override 
    public void onResponse(Call<DeviceModel> call, Response<DeviceModel> 
           response) { 
     //How do I get access to the {"success" : true} object sent as a response form the endpoint after I posted. 
    } 

    @Override 
    public void onFailure(Call<DeviceModel> call, Throwable t) { 
     Log.d("Failure", "ON FAILURE" + "Failure"); 
    } 
}); 

現在在我的節點API如果保存的對象是成功的我返回JSON對象:{"success" : true}

但在上面的onResponse方法中response變量的參數類型爲Response<DeviceModel>。如何從onResponse()的上述方法中提取我從下面的節點API發回的{"success" : true}對象?有沒有辦法做到這一點?

router.post('/insert', function(req, res) { 
    //Create Object 
    var obj = new Device({ 
    }); 

    obj.save(function(err) { 
     if (err) { 
      console.log("SAVE NOT SUCCESSFUL"); 
     }else { 
      console.log("SAVE SUCCESS"); 
      res.json({ 
       "success" : true 
      }); 
     } 
    }); 
}); 
+2

如果響應不是'DeviceModel',爲什麼要使用'Call '? – njzk2

回答

1

你應該轉到OkHTTP文檔,這是Retrofit在底層使用的。

response.body()應該給你一個DeviceModel這似乎是一個陌生的名字爲一類,只會有一個boolean success場,所以我覺得你的改造API設計需要一些工作......

注意:響應主體只能被消耗一次並且它必須關閉

例如,一試,與資源

Call<DeviceModel> call = client.newCall(request); 
    call.enqueue(new Callback<DeviceModel>() { 
    public void onResponse(Call<DeviceModel> call, Response<DeviceModel> response) throws IOException { 
     try (DeviceModel model = response.body()) { 
     // TODO: use model 
     } 
    } 

    public void onFailure(Call call, IOException e) { 
     ... // Handle the failure. 
    } 
    }); 

來源 - ResponseBody

您可以使用response.body().string()來獲取原始的JSON字符串,如果你真的想這樣做。

+0

哦,我的DeviceModel有超過6個字段。但我只想發回一個只有JSON對象'{「success」:true}'的響應。我想檢查'onResponse'回調中的'success'鍵並測試它是否爲true,然後在應用程序中執行某些操作(如果設備已成功保存)。或者將response.body永遠是一個DeviceModel對象? – CapturedTree

+0

如果您使用「致電」,那麼您將得到一個「響應」,即「DeviceModel」。您可以輕鬆地重寫您的createDevice API方法來返回其他東西 –

+0

但是,實際上,您不應該返回由數據庫創建的整個對象嗎?難道你不能安全地假設來自API的200響應代碼是「成功」嗎? –