- 實(shí)體類
package com.xqxf.dto;
import com.xqxf.domain.User;
/**
* Package com.xqxf.dto
*
* author liyaocai
*
* date 2017/10/7 20:24
*
* Description:
*
* version V1.0
*/
public class UserDto {
private String uId;
private User user;
public UserDto() {
}
public String getuId() {
return uId;
}
public void setuId(String uId) {
this.uId = uId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
自定義序列化類繼承JsonDeserializer
- UserDeserializer類
package com.xqxf.utils.Json;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.xqxf.domain.User;
import com.xqxf.dto.UserDto;
import java.lang.reflect.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Package com.xqxf.utils
*
* author liyaocai
*
* date 2017/10/7 19:49
*
* Description:
*
* version V1.0
*/
public class UserDeserializer implements JsonDeserializer<UserDto>{
Logger logger= LoggerFactory.getLogger(UserDeserializer.class);
public UserDeserializer() {
}
@Override
public UserDto deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject jsonObject=jsonElement.getAsJsonObject();
User user=new User();
UserDto userDto=new UserDto();
user.setNickName(jsonObject.get("info").getAsJsonObject().get("nickName").getAsString());
// user.setPermission(jsonObject.get("info").getAsJsonObject().get("permission").getAsString());
// user.setUserName(jsonObject.get("info").getAsJsonObject().get("userName").getAsString());
user.setAddress(jsonObject.get("info").getAsJsonObject().get("address").getAsString());
user.setCompany(jsonObject.get("info").getAsJsonObject().get("company").getAsString());
user.setDepartment(jsonObject.get("info").getAsJsonObject().get("department").getAsString());
user.setPhone(jsonObject.get("info").getAsJsonObject().get("phone").getAsString());
user.setTel(jsonObject.get("info").getAsJsonObject().get("tel").getAsString());
userDto.setuId(jsonObject.get("uId").getAsString());
userDto.setUser(user);
return userDto;
}
}
- 使用建造者模式構(gòu)件gson實(shí)例
Gson gson = new GsonBuilder()//建造者模式設(shè)置不同的配置
.serializeNulls()//序列化為null對(duì)象
.setDateFormat("yyyy-MM-dd HH:mm:ss") //設(shè)置日期的格式
.disableHtmlEscaping()//防止對(duì)網(wǎng)址亂碼 忽略對(duì)特殊字符的轉(zhuǎn)換
.excludeFieldsWithoutExposeAnnotation()
// 使用自定義適配器
.registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory())
.registerTypeAdapter(UserDto.class,new UserDeserializer())
.registerTypeAdapter(WorkOrderDto.class,new WorkOrderDeserializer())
.create();
關(guān)于JsonDeserializer的介紹請(qǐng)查看http://www.importnew.com/16786.html