2016-03-09 20 views
7

我需要通過改造2送下一個JSON創建@Body轉換器:改造:無法爲

{ 
    "Inspection": { 
     "UUID": "name", 
     "ModifiedTime": "2016-03-09T01:13", 
     "CreatedTime": "2016-03-09T01:13", 
     "ReviewedWith": "name2", 
     "Type": 1, 
     "Project": { 
      "Id": 41 
     }, 
     "ActionTypes": [1] 
    } 
} 

隨着頭:Authorization: access_token_value

我嘗試這樣做:

//header parameter 
String accessToken = Requests.getAccessToken(); 

JsonObject obj = new JsonObject(); 
JsonObject inspection = new JsonObject(); 

inspection.addProperty("UUID","name"); 
inspection.addProperty("ModifiedTime","2016-03-09T01:13"); 
inspection.addProperty("CreatedTime","2016-03-09T01:13"); 
inspection.addProperty("ReviewedWith","name2"); 
inspection.addProperty("Type","1"); 

JsonObject project = new JsonObject(); 
project.addProperty("Id", 41); 

inspection.add("Project", project); 
obj.add("Inspection", inspection); 

Retrofit restAdapter = new Retrofit.Builder() 
     .baseUrl(Constants.ROOT_API_URL) 
     .addConverterFactory(GsonConverterFactory.create()) 
     .addConverterFactory(ScalarsConverterFactory.create()) 
     .build(); 
IConstructSecureAPI service = restAdapter.create(IConstructSecureAPI.class); 
Call<JsonElement> result = service.addInspection(accessToken, obj); 
JsonElement element = result.execute().body(); 

但每次我收到異常:java.lang.IllegalArgumentException: Unable to create @Body converter for class com.google.gson.JsonObject (parameter #2)

我該如何發送?或者任何其他的想法,我怎麼能做到這一點。你甚至可以用簡單的參數String給我提供json參數。它會適合我

+0

請發佈IConstructSecureAPI只是爲了知道您如何構建您的請求。 –

回答

10

解決方案:接下來在你的界面 聲明體值:

@Body RequestBody body ,敷字符串JSON對象:

RequestBody body = RequestBody.create(MediaType.parse("application/json"), obj.toString());

1

Body使用單個請求對象,申報你的請求對象如下

class Inspection { 
    String UUID; 
    //..... add your fields 
    Project project;  
} 

class Product 
{ 
    int Id; 
    //....... add your fields 
} 

我假設你的服務IConstructSecureAPI端點是:

@GET(...) // change based on your api GET/POST 
Call<Response> addInspection(
    @Header("Authorization") String accesstoken, 
    @Body Inspection request 
); 

,你可以聲明你的慾望Response

檢查這個answer,其使用HashMap而不是類。

0

您可以使用攔截器來發送認證頭在每個請求

class AuthorizationInterceptor implements Interceptor { 

    @Override 
    public Response intercept(Chain chain) throws IOException { 
     Request originalRequest = chain.request(); 
     String authorizationToken = AuthenticationUtils.getToken(); 
     Request authorizedRequest = originalRequest.newBuilder() 
      .header("Authorization", authorizationToken) 
      .build(); 
     return chain.proceed(authorizedRequest); 
    } 
}