Jackson 使用

// 序列化出来的 JSON, 不包含值为 NULL 类型字段。
mapper.setSerializationInclusion(Include.NON_NULL);  

  

 Jackson provides a few different mechanisms to configure handling of "extra" JSON elements. Following is an example of configuring the ObjectMapper to not FAIL_ON_UNKNOWN_PROPERTIES.

 出现这种 error, 一般是没有该字段造成的,或都是字段名字写错了。

import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    // { "aaa":"111", "bbb":"222", "ccc":"333" }
    String jsonInput = "{ "aaa":"111", "bbb":"222", "ccc":"333" }";

    ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    Test test = mapper.readValue(jsonInput, Test.class);
  }
}

class Test
{
  String aaa;
  String bbb;
}

 格式化日期代码如下:

mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

 空值不显示:

 mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

  

原文地址:https://www.cnblogs.com/chenzc/p/4074190.html