
io.github.ximutech.spore.retrofit.HttpConvertFactory Maven / Gradle / Ivy
package io.github.ximutech.spore.retrofit;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
/**
* retrofit call 转换器
*
* @author ximu
*/
public class HttpConvertFactory extends Converter.Factory {
private String charset = "utf-8";
private JacksonConverterFactory jacksonConverterFactory;
public HttpConvertFactory(String charset, boolean snake) {
this.charset = charset;
ObjectMapper mapper = new ObjectMapper();
if (snake) {
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
}
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
this.jacksonConverterFactory = JacksonConverterFactory.create(mapper, charset);
}
@Override
public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
switch (defineType(type)) {
case 0:
return jacksonConverterFactory.responseBodyConverter(type, annotations, retrofit);
case 1:
return (Converter) value -> Byte.valueOf(value.string());
case 2:
return (Converter) value -> Short.valueOf(value.string());
case 3:
return (Converter) value -> Integer.valueOf(value.string());
case 4:
return (Converter) value -> Long.valueOf(value.string());
case 5:
return (Converter) value -> Double.valueOf(value.string());
case 6:
return (Converter) value -> Float.valueOf(value.string());
case 7:
return (Converter) value -> value.string().charAt(0);
case 8:
return (Converter) value -> new String(value.bytes(), charset);
default:
return jacksonConverterFactory.responseBodyConverter(type, annotations, retrofit);
}
}
@Override
public Converter, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
switch (defineType(type)) {
case 8:
return (Converter
© 2015 - 2025 Weber Informatics LLC | Privacy Policy