在项目中以前用fastjson,后来发现SpringBoot里集成有Jackson
编程习惯原因,以后只使用Jackson
写一下常用到的一些使用
* ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。
* ObjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。
* writeValue(File arg0, Object arg1)把arg1转成json序列,并保存到arg0文件中。
* writeValue(OutputStream arg0, Object arg1)把arg1转成json序列,并保存到arg0输出流中。
* writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组。
* writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串。
1.格式化问题。
常用的有日期格式化:@JsonFormat(pattern = "yyMMddHHmmss", timezone = "GMT+8")
2.使用类来序列化和反序列化
public class DeserializeDouble2 extends JsonDeserializer<Double> {
@Override
public Double deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException {
double value = parser.getDoubleValue();
return Double.valueOf(value / 100);
}
}
在类里使用
@JsonDeserialize(using = DeserializeDouble3.class)
private Double money;
3.Jackson可以作一个全局设置,作一个全局类
public class JsonUtil{
private static ObjectMapper mapper = new ObjectMapper();
static {
// 解决实体未包含字段反序列化时抛出异常
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 对于空的对象转json的时候不抛出错误
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// 允许属性名称没有引号
mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// 允许单引号
mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
}
public static String toJsonString(Object obj) {
String json = null;
try {
json = mapper.writeValueAsString(obj);
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
public static <T> T toJsonClass(String json, Class<T> beanType) {
T t = null;
try {
t = mapper.readValue(json, beanType);
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
}