Tuesday, 3 December 2019

Convert TimeZone of Date in RequestBody of retrofit

I'm using retrofit for making calls to server, I have requestBody like this:

class MyRequestBody {
String id;
Date date;
}

I want to convert timezone of date object in requestBody.

I tried these things:

Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS zzz")
.create();

Retrofit.Builder adapterBuilder = new Retrofit
.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonCustomConverterFactory.create(gson))

class GsonCustomConverterFactory extends Converter.Factory
{
    public static GsonCustomConverterFactory create(Gson gson) {
        return new GsonCustomConverterFactory(gson);
    }

    private final Gson gson;
    private final GsonConverterFactory gsonConverterFactory;

    private GsonCustomConverterFactory(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        this.gson = gson;
        this.gsonConverterFactory = GsonConverterFactory.create(gson);
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        if(type.equals(String.class))
            return new GsonResponseBodyConverterToString<Object>(gson, type);
        else
            return gsonConverterFactory.responseBodyConverter(type, annotations, retrofit);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        return gsonConverterFactory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
    }
}

but above code can only control the pattern of date not timezone. I want to change timezone also. Thanks!



from Convert TimeZone of Date in RequestBody of retrofit

No comments:

Post a Comment