Fastxml 简单常用注解学习笔记
如下User类
package com.usoft;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.math.BigDecimal;
import java.util.Date;
/**
* Created by xinxingegeya on 2015/3/7.
*/
@JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class)
@JsonIgnoreProperties(value = {"enabled", "age", "bigDecimal"}, ignoreUnknown = true)
public class User {
private String username;
@JsonIgnore
private String passwd;
@JsonFormat(pattern = "yyyy-MM-dd")
@JsonDeserialize(using = CustomDateDeserialize.class)
private Date createDate;
private boolean enabled;
private int age;
private BigDecimal bigDecimal;
@JsonSerialize(using = CustomDoubleSerialize.class)
private double helloDouble;
// 该属性没有setter和getter方法,如果想要序列化必须标注该注解
@JsonProperty(value = "belong_to_role")
private boolean belongToRole = false;
public double getHelloDouble() {
return helloDouble;
}
public void setHelloDouble(double helloDouble) {
this.helloDouble = helloDouble;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public BigDecimal getBigDecimal() {
return bigDecimal;
}
public void setBigDecimal(BigDecimal bigDecimal) {
this.bigDecimal = bigDecimal;
}
}
相关的类
package com.usoft;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CustomDateDeserialize extends JsonDeserializer<Date> {
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
Date date = null;
try {
date = sdf.parse(jp.getText());
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
package com.usoft;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.text.DecimalFormat;
public class CustomDoubleSerialize extends JsonSerializer<Double> {
private DecimalFormat df = new DecimalFormat("##.00");
@Override
public void serialize(Double value, JsonGenerator jgen,
SerializerProvider provider) throws IOException {
jgen.writeString(df.format(value));
}
}
测试类,
package com.usoft;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.util.Date;
/**
* Created by xinxingegeya on 2015/3/7.
*/
public class TestJson {
private static final JsonMapper mapper = new JsonMapper();
private static Logger logger = LoggerFactory.getLogger(TestJson.class);
/**
* fastxml序列化json
*/
@Test
public void test76() {
User user = new User();
user.setAge(19);
user.setBigDecimal(new BigDecimal(12));
user.setCreateDate(new Date());
user.setEnabled(true);
user.setPasswd("122");
user.setUsername("admin");
user.setHelloDouble(3.1);
String json = mapper.toJson(user);
logger.info(json);
}
@Test
public void testu68() {
String helloJson = "{\"username\":\"admin\",\"passwd\":\"122\",\"createDate\":\"2015-03-07 13:25:47\",\"birthday\":\"2015-03-07 13:25:47\"}";
User user = mapper.fromJson(helloJson, User.class);
logger.info(user.toString());
logger.info(user.getCreateDate().toString());
}
}
更多详见:http://blog.csdn.net/sdyy321/article/details/40298081
最后附上一个Json序列化的工具类,该工具类是从springside项目中拿来的。
package com.usoft;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class JsonMapper {
private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
private ObjectMapper mapper;
public JsonMapper() {
this(null);
}
public JsonMapper(JsonInclude.Include include) {
this.mapper = new ObjectMapper();
//设置日期格式当使用jackson在处理时间时,默认是将时间输出为timestamps格式
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
this.mapper.setDateFormat(fmt);
//设置输出时包含属性的风格
if (include != null) {
this.mapper.setSerializationInclusion(include);
}
//设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
this.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
//Include.Include.ALWAYS 默认
//Include.NON_DEFAULT 属性为默认值不序列化
//Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化
//Include.NON_NULL 属性为NULL 不序列化
/**
* 属性为 空(“”) 或者为 NULL 都不序列化
*
* @return
*/
public static JsonMapper nonEmptyMapper() {
return new JsonMapper(JsonInclude.Include.NON_EMPTY);
}
/**
* 属性为默认值不序列化
*
* @return
*/
public static JsonMapper nonDefaultMapper() {
return new JsonMapper(JsonInclude.Include.NON_DEFAULT);
}
/**
* 属性为NULL不序列化
*
* @return
*/
public static JsonMapper nonNullMapper() {
return new JsonMapper(JsonInclude.Include.NON_NULL);
}
/**
* Object可以是POJO,也可以是Collection或数组。
* 如果对象为Null, 返回"null".
* 如果集合为空集合, 返回"[]".
*
* @param object
* @return
*/
public String toJson(Object object) {
try {
return this.mapper.writeValueAsString(object);
} catch (IOException e) {
JsonMapper.logger.warn("write to json string error:" + object, e);
System.out.println(e.getMessage());
return null;
}
}
/**
* 反序列化POJO或简单Collection如List.
*
* 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合.
*
* 如需反序列化复杂Collection如List, 请使用fromJson(String,JavaType)
*
* @param jsonString
* @param clazz
* @return
* @see #fromJson(String, com.fasterxml.jackson.databind.JavaType)
*/
public T fromJson(String jsonString, Class clazz) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return this.mapper.readValue(jsonString, clazz);
} catch (IOException e) {
JsonMapper.logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 反序列化复杂Collection如List, 先使用函數createCollectionType构造类型,然后调用本函数.
*
* @param jsonString
* @param javaType
* @return
* @see #createCollectionType(Class, Class...)
*/
public T fromJson(String jsonString, JavaType javaType) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return (T) this.mapper.readValue(jsonString, javaType);
} catch (IOException e) {
JsonMapper.logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 構造泛型的Collection Type如:
* ArrayList,
* 则调用constructCollectionType(ArrayList.class,MyBean.class)
* HashMap, 则调用(HashMap.class,String.class, MyBean.class)
*
* @param collectionClass
* @param elementClasses
* @return
*/
public JavaType createCollectionType(Class collectionClass,
Class... elementClasses) {
return this.mapper.getTypeFactory().constructParametricType(
collectionClass, elementClasses);
}
/**
* @param jsonString
* @param object
* @return
*/
public T update(String jsonString, T object) {
try {
return (T) this.mapper.readerForUpdating(object).readValue(
jsonString);
} catch (JsonProcessingException e) {
JsonMapper.logger.warn("update json string:" + jsonString
+ " to object:" + object + " error.", e);
} catch (IOException e) {
JsonMapper.logger.warn("update json string:" + jsonString
+ " to object:" + object + " error.", e);
}
return null;
}
/**
* @param functionName
* @param object
* @return
*/
public String toJsonP(String functionName, Object object) {
return this.toJson(new JSONPObject(functionName, object));
}
}
====================================END====================================