我们请求后台获得json的时候,往往不能获得我们比较喜欢的数据类型.例如:时间传给字符串,boolean 传给int类型:
如图:
{
time:"20180524",
isLoveMe:1//1代表true,0:代表false
}
Q:这个时候我们怎么方便的直接把time编程date,isLoveMe编程Boolean呢?
A:这个时候我们使用Gson中的@JsonAdapter标签
从而把该json变成以下的JavaBean:
class Resule{
@JsonAdapter(xxxx.class)
Date time;
@JsonAdapter(xxxx.class)
Boolean isLoveMe;
}
JsonAdapter里面需要的参数就是一个继承于TypeAdapter的子类,在这里我们等于改写了json的解析方式,从而把”20180524”–>变成–>Date;把1–>Boolean
其实TypeAdapter是个抽象方法里面就两个方法,通过名字很好理解:
public abstract class TypeAdapter<T> {
/**
将javabean字段变成对应的json
*/
public abstract void write(JsonWriter out, T value) throws IOException;
/**
将json变成对应的javabean字段
*/
public abstract T read(JsonReader in) throws IOException;
}
举个栗子
public class BooleanTypeAdapter extends TypeAdapter<Boolean> {
@Override
public void write(JsonWriter out, Boolean value) throws IOException {
if(value == null){
out.nullValue();
}else if(value){
out.jsonValue("1");
}else {
out.jsonValue("0");
}
}
@Override
public Boolean read(JsonReader in) throws IOException {
if(in.peek() == JsonToken.NULL){
in.nextNull();
return false;
}
String value = in.nextString();
if(value.equalsIgnoreCase("1")){
return true;
}else if(value.equalsIgnoreCase("0")){
return false;
} else {
throw new IllegalArgumentException("unknown value for boolean, must be 1 or 0");
}
}
}
实际操作
class Resule {
String time;
@JsonAdapter(BooleanTypeAdapter.class)
Boolean isLoveMe;
@Override
public String toString() {
return "Resule{" +
"time='" + time + '\'' +
", isLoveMe=" + isLoveMe +
'}';
}
}
开炮:
@Test
public void testGons() {
String str = "{\n" +
"\ttime:\"20180524\",\n" +
"\tisLoveMe:1//1代表true,0:代表false\n" +
"}";
Resule resule = new Gson().fromJson(str, Resule.class);
System.out.println(resule);
}
结果:
Resule{time='20180524', isLoveMe=true}
很明显,isLoveMe字段变成了Beanlean
那么String 怎么转变成Date呢?
由于
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
public @interface JsonAdapter {
/** Either a {@link TypeAdapter} or {@link TypeAdapterFactory}. */
Class<?> value();
}
只能传进去一个参数:无法自由的转变时间的格式,可以换一个方式:
public class DateTypeAdapter_yyyyMMdd extends DynamicDateTypeAdapter{
public DateTypeAdapter_yyyyMMdd() {
super("yyyyMMdd");
}
}
public abstract class DynamicDateTypeAdapter extends TypeAdapter<Date> {
private static final Map<String,DateFormat> DATE_FORMAT_MAP = new HashMap<>();
private final String format;
private DateFormat dateFormat;
//由于字段解析会大量调用该方法,这里写成static final 更加快
private static final DateFormat HHmm_DateFormat = new SimpleDateFormat("HHmm",Locale.CHINA);
private static final DateFormat yyyyMMdd_DateFormat = new SimpleDateFormat("yyyyMMdd",Locale.CHINA);
private static final DateFormat yyyyMMddHHmm_DateFormat = new SimpleDateFormat("yyyyMMddHHmm",Locale.CHINA);
private static final DateFormat yyyyMMddHHmmss_DateFormat = new SimpleDateFormat("yyyyMMddHHmmss",Locale.CHINA);
protected DynamicDateTypeAdapter(@NonNull String format) {
this.format = format;
dateFormat = DATE_FORMAT_MAP.get(format);
if(dateFormat == null){
dateFormat = new SimpleDateFormat(format, Locale.CHINA);
DATE_FORMAT_MAP.put(format,dateFormat);
}
}
@Override
public void write(JsonWriter out, Date value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.jsonValue(dateFormat.format(value));
}
}
@Override
public Date read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
String jsonValue = in.nextString();
// 4 HHmm
// 8 yyyyMMdd
// 12 yyyyMMddHHmm
// 14 yyyyMMddHHmmss
if ("19000101".equals(jsonValue)) {
return null;
}
if ("190001010000".equals(jsonValue)) {
return null;
}
if(StringUtils.isEmpty(jsonValue)){
return null;
}
try {
if(jsonValue.length() == 4){
return HHmm_DateFormat.parse(jsonValue);
}else if(jsonValue.length() == 8){
return yyyyMMdd_DateFormat.parse(jsonValue);
}else if(jsonValue.length() == 12){
return yyyyMMddHHmm_DateFormat.parse(jsonValue);
}else if(jsonValue.length() == 14){
return yyyyMMddHHmmss_DateFormat.parse(jsonValue);
}else{
throw new IllegalArgumentException("unknown date date format, must be " + format);
}
} catch (ParseException e) {
throw new IllegalArgumentException("unknown date date format, must be " + format, e);
}
}
}
开始实践;
@Test
public void testGons() {
String str = "{\n" +
"\ttime:\"20180524\",\n" +
"\tisLoveMe:1//1代表true,0:代表false\n" +
"}";
Resule resule = new Gson().fromJson(str, Resule.class);
System.out.println(resule);
}
class Resule {
@JsonAdapter(DateTypeAdapter_yyyyMMdd.class)
Date time;
@JsonAdapter(BooleanTypeAdapter.class)
Boolean isLoveMe;
@Override
public String toString() {
return "Resule{" +
"time='" + time + '\'' +
", isLoveMe=" + isLoveMe +
'}';
}
}
结果
Resule{time='Thu May 24 00:00:00 CST 2018', isLoveMe=true}
time 已经变成了date格式了