2016-03-09 23 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); 
    } 
}