相关文章:
http://dreamhead.blogbus.com/logs/230244031.html
jackson 是 java 最常用的json 序列化 和反序列化工具。
pom.xml 引入
<dependency>
<!-- note: typically only ".0" patch version exists for core annotations -->
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.3.3</version>
</dependency>
1、同一个model中,基于注解的序列化其中部分字段的方式
class Views {
static class Public {}
static class ExtendedPublic extends Public{}
}
class Thing {
@JsonView(Views.Public.class) Integer id = 100;
@JsonView(Views.Public.class) String email = "[email protected]";
@JsonView(Views.ExtendedPublic.class) String name = "admin";
}
/**
* 同一个model 序列化其中部分字段的方式
* @author wangxinchun
*/
public class JsonViewUseage {
@Test
public void testExtendedPublic() throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithView(Views.ExtendedPublic.class).writeValue(System.out, new Thing());
//{"id":100,"email":"[email protected]","name":"admin"}
}
@Test
public void testPublic() throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithView(Views.Public.class).writeValue(System.out, new Thing());
//{"id":100,"email":"[email protected]"}
}
@Test
public void testObject() throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithView(Object.class).writeValue(System.out, new Thing());
//{}
}
}
2、基于泛型的序列化处理。
class User {
private String username = "admin";
private String password = "password";
public String getUsername() {return username;}
public void setUsername(String username) {this.username = username;}
public String getPassword() {return password;}
public void setPassword(String password) {this.password = password;}
}
public class TypeReferenceUseage {
public static void main(String[] args) throws Exception {
Map<String, User> map = new LinkedHashMap<String, User>();
map.put("532002108", new User());
StringWriter sw = new StringWriter();
ObjectMapper mapper = new ObjectMapper();
JsonGenerator jg = new JsonFactory().createGenerator(sw);
mapper.writeValue(jg, map);
System.out.println(sw.toString());
//{"532002108":{"username":"admin","password":"password"}}
Map<String,User> newMap = mapper.readValue(sw.toString(), new TypeReference<Map<String,User>>(){});
//password
System.out.println(newMap.get("532002108").getPassword());
}
}
public class PayCenterResponse<T> {
@SuppressWarnings("rawtypes")
public static PayCenterResponse EMPTY_RESPONSE = new PayCenterResponse(false,"","");
protected boolean ret;
protected String errcode;
protected String errmsg;
private List<T> data;
/***略***/
}
private PayCenterResponse<DaiKouResponseData> wrapDaiKouResponse(String responseText){
if(StringUtils.isEmpty(responseText)){
return PayCenterResponse.EMPTY_RESPONSE;
}
PayCenterResponse<DaiKouResponseData> result = JsonUtils.readJsonToObject(responseText, new TypeReference<PayCenterResponse<DaiKouResponseData>>(){});
return result;
}
public static <T> T readJsonToObject(String data,TypeReference<T> reference) {
T t = null;
try {
t = mapper.readValue(data, reference);
}catch (IOException e) {
logger.error("data {}",data, e);
}
return t;
}
3、字段名字替换。 jackson 注解实现。
class Job{
@JsonProperty("jName")
private String jobName = "java工程师";
@JsonProperty("jId")
private int jobId = 1;
@JsonIgnore
private String jobNo = "hr177739477894";
@JsonFormat(pattern = "yyyy-MM-dd")
private Date createDate = new Date();
}
@Test
public void testJacksonAnnotation() throws Exception{
ObjectMapper maper = new ObjectMapper();
maper.setAnnotationIntrospector(new JacksonAnnotationIntrospector());
maper.writeValue(System.out, new Job());
}
4、字段重命名。jaxb注解。
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Job2{
@XmlElement(name = "jName")
private String jobName = "java工程师";
@XmlElement(name = "jid")
private int jobId = 2;
@XmlTransient
private String jobNo = "hr177739477894";
@XmlJavaTypeAdapter(value = LocalDateAdapter.class)
private Date createDate = new Date();
}
class LocalDateAdapter extends XmlAdapter<String,Date>{
@Override
public Date unmarshal(String v) throws Exception {
return new SimpleDateFormat("yyyy-MM-dd").parse(v);
}
@Override
public String marshal(Date v) throws Exception {
return new SimpleDateFormat("yyyy-MM-dd").format(v);
}
}
@Test
public void testJaxbAnnotation() throws Exception{
ObjectMapper maper = new ObjectMapper();
maper.setAnnotationIntrospector(new JaxbAnnotationIntrospector());
maper.writeValue(System.out, new Job2());
}