配置日期格式
默认情况下,Jackson 会将日期转成 long 值,我们也可以设置日期格式,将日期转成字符串
,下面是一个简单的例子。
package shangbo.jackson.demo5;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.databind.ObjectMapper;
public class App {
public static void main(String[] args) throws Exception {
// 实例化 ObjectMapper 对象
ObjectMapper objectMapper = new ObjectMapper();
// 设置日期格式
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
objectMapper.setDateFormat(dateFormat);
// 将对象转成 json
String json = objectMapper.writeValueAsString(newPerson());
System.out.println(json);
// 将 json 转成对象
Person shangbo = objectMapper.readValue(json, Person.class);
System.out.println(shangbo);
}
private static Person newPerson() {
Person shangbo = new Person();
shangbo.setFirstname("Bo");
shangbo.setLastname("Shang");
shangbo.setBrithday(new Date());
return shangbo;
}
}
忽略未知字段
通常 JSON 消息和 Java 类的字段必须相对应,否则解析 JSON 会报错,当然我们也可以通过配置使它不报错。
package shangbo.jackson.demo6;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class App {
public static void main(String[] args) throws Exception {
// 实例化 ObjectMapper 对象
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 忽略未知字段
// json 消息
String json = "{\"firstname\":\"Bo\",\"lastname\":\"Shang\",\"brithday\":\"2019-05-25\"}";
// 将 json 转成对象,忽略 brithday
Person shangbo = objectMapper.readValue(json, Person.class);
System.out.println(shangbo);
}
}
原文链接:https://blog.csdn.net/shangboerds/article/details/90543656