通过使用getSerializationConfig()方法对ObjectMapper进行正确配置,Java Object to JSON

时间:2017-03-11 14:40:37

标签: json jackson

我正在使用Jackson版本2.8.7

我有一个Person对象,按以下方式打印:

object: Persona [id=087, nombre=Leonardo, apellido=Jordan, fecha=Sun Jul 05 00:00:00 PET 1981] 

观察日期部分Sun Jul 05 00:00:00 PET 1981

我从这两篇有价值的帖子中研究了如何将对象(实体)和 Date 对象序列化为JSON格式:

当我使用时:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getSerializationConfig().with(dateFormat);

ObjectWriter ow = objectMapper.writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);

观察两件事:

  • objectMapper.getSerializationConfig().with(dateFormat);
  • writer()

我总是得到:

json: {
  "id" : "087",
  "nombre" : "Leonardo",
  "apellido" : "Jordan",
  "fecha" : 363157200000
} 

观察363157200000值,不带引号。 因此它没有用。

但如果使用:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
ObjectMapper objectMapper = new ObjectMapper();
//objectMapper.getSerializationConfig().with(dateFormat);

ObjectWriter ow = objectMapper.writer(dateFormat).withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);

观察两件事:

  • //objectMapper.getSerializationConfig().with(dateFormat);发表了评论
  • writer(dateFormat)参数

我总是得到:

json: {
  "id" : "087",
  "nombre" : "Leonardo",
  "apellido" : "Jordan",
  "fecha" : "1981-07-05"
} 

现在有效。

  1. 为什么第一种方法不起作用?
  2. 获得预期行为的第一种方法的正确配置是什么?
  3. 如果我需要通过getSerializationConfig().with(...)方法应用更多功能,我对第一种方法更感兴趣。

1 个答案:

答案 0 :(得分:1)

第一种方法不起作用,因为 with()会创建并返回一个新的SerializationConfig,因此它不会应用于您正在使用的objectMapper实例。这是该方法的javadoc:

/**
 * Fluent factory method that will construct and return a new configuration
 * object instance with specified features enabled.
 */

当您想要将一个ObjectMapper实例的配置重用于另一个ObjectMapper实例时,可以使用此方法。使用 with()方法,您可以指定要应用于配置副本的任何差异。

例如,这里我们使用映射器1的配置,具有不同的日期格式,用于mapper2。映射器1未更改。

    ObjectMapper mapper2 = new ObjectMapper();
    mapper2.setConfig(mapper1.getSerializationConfig().with(otherDateFormat));

为了将dateformat应用于每个案例,您可以使用 setDateFormat(DateFormat)

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(dateFormat);