Retrofit2将身体贴为Json

时间:2016-02-12 01:21:32

标签: java android json retrofit retrofit2

我正在更新Retrofit以使用 Retrofit2 ,我已经设法做了很多事情GET,POST,PUT ......

但我有一个请求,我必须发送一个完整的JSON,我设法在Retrofit 1.9中做到了,但在Retrofit2中没有支持它。

import retrofit.mime.TypedString;

public class TypedJsonString extends TypedString {
    public TypedJsonString(String body) {
        super(body);
    }

    @Override
    public String mimeType() {
        return "application/json";
    }
}

如何使其改造2

2 个答案:

答案 0 :(得分:6)

你可以简单地强迫标题为Call call = myService.postSomething( RequestBody.create(MediaType.parse("application/json"), jsonObject.toString())); call.enqueue(...) (正如你所做的那样)并将其作为字符串发送......

...

interface MyService {
    @GET("/someEndpoint/")
    Call<ResponseBody> postSomething(@Body RequestBody params);
}

然后..

{{1}}

或者我在这里遗漏了什么?

答案 1 :(得分:4)

I Fixed the problem with the next code

public interface LeadApi {
    @Headers( "Content-Type: application/json" )
    @POST("route")
    Call<JsonElement> add(@Body JsonObject body);
}

Note the difference I'm Using Gson JsonObject. And in the creation of the adapter i use a GSON converter.

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

public class APIAdapter {
    public static final String BASE_URL = "BaseURL";

    private static Retrofit restAdapter;
    private static APIAdapter instance;

    protected APIAdapter() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
        restAdapter = new Retrofit.Builder().baseUrl(BASE_URL).client(client).addConverterFactory(GsonConverterFactory.create()).build();
    }

    public static APIAdapter getInstance() {
        if (instance == null) {
            instance = new APIAdapter();
        }
        return instance;
    }

    public Object createService(Class className) {
        return restAdapter.create(className);
    }

}

Take care to have the same version of Retrofit and it's coverter. It lead to errors!