• jackson 常见问题


    org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type

    org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class test.jackson.Employee]: can not instantiate from JSON object (need to add/enable type information?)
     at [Source: c: empemployee.json; line: 1, column: 2]
        at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
        at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:483)
        at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:350)
        at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2395)
        at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1549)
        at test.jackson.JSONToJavaExample.main(JSONToJavaExample.java:19)

    一般来说,解决上面问题从下面几个方面入手:

    1、是否缺少默认构造函数

    2、是否是类的访问修饰符问题,即jackson访问不到。

    jackson 的UnrecognizedPropertyException错误

    java代码如下:

    1. public class Student implements Serializable{ 
    2.     private static final long serialVersionUID = 685922460589405829L; 
    3.  
    4.     private String name; 
    5.     private String age; 
    6.  
    7.    /*get set略*/ 

    json字符串如下:

    "{"address":"hunan","name":"china","age":"5000"}"

    这种情况下,使用jackson从string转换为object的时候,会抛出下面异常:

    1. java.lang.IllegalArgumentException: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "address" (Class util.Student), not marked as ignorable 

    意思是说Student类里没有address这个属性,所以无法正常转化,同时还指明了not marked as ignorable,即没有标明可忽略的特性

    解决方案:

    1、在类上添加忽略声明

    @JsonIgnoreProperties(ignoreUnknown=true)

    2、更改str2obj方法

       ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        projectVO = objectMapper.readValue(yourjsonstring, Test.class);

     

    Jackson annotation - How to rename element names?

    you can rename a property just adding

    @JsonProperty("contractor")

    And by default Jackson use the getter and setter to serialize and deserialize.

     

    Using a custom JsonSerializer.

    public class Response { private String status; private String error; @JsonProperty("p") @JsonSerialize(using = CustomSerializer.class) private Object data; // ... } public class CustomSerializer extends JsonSerializer<Object> { public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeObjectField(value.getClass().getName(), value); jgen.writeEndObject(); } }

    Could not read JSON: Can not construct instance of java.util.Date from String value '2012-07-21 12:11:12': not a valid representation

    1. "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    2. "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
    3. "EEE, dd MMM yyyy HH:mm:ss zzz"
    4. "yyyy-MM-dd"

    当尸实体中存在Date类型,但是json字符串中是字符串类型

    只支持以上几种格式否则报错

    1.  
    2. /** 
    3. *  java日期对象经过Jackson库转换成JSON日期格式化自定义类 
    4. * @author godfox 
    5. * @date 2010-5-3 
    6. */ 
    7. public class CustomDateSerializer extends JsonSerializer<Date> { 
    8.  
    9.         @Override 
    10.         public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { 
    11.                 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
    12.                 String formattedDate = formatter.format(value); 
    13.                 jgen.writeString(formattedDate); 
    14.         } 

    然后在你的POJO上找到日期的get方法

    Java代码  收藏代码

    1. @JsonSerialize(using = CustomDateSerializer.class)  
    2.        public Date getCreateAt() {  
    3.                return createAt;  
    4.        }  

    1. @JsonSerialize(using = CustomDateSerializer.class
    2.        public Date getCreateAt() { 
    3.                return createAt; 
    4.        } 
    1. //null的JSON序列 
    2.     private class NullSerializer extends JsonSerializer<Object> { 
    3.         public void serialize(Object value, JsonGenerator jgen, 
    4.                 SerializerProvider provider) throws IOException, 
    5.                 JsonProcessingException { 
    6.             jgen.writeString(""); 
    7.         } 
    8.     } 

    在spring的配置文件中定义这个自定义的Mapper

    在spring的配置文件中定义这个自定义的Mapper

    Xml代码 收藏代码

    1. <!-- 启动 MVC注解 -->
    2. <mvc:annotation-driven>
    3. <mvc:message-converters>
    4. <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    5. <property name="objectMapper" ref="customObjectMapper" />
    6. </bean>
    7. </mvc:message-converters>
    8. </mvc:annotation-driven>
    9. <!-- 自定义的JSON ObjectMapper -->
    10. <bean id="customObjectMapper" class="com.xixi.web4j.util.CustomObjectMapper" />

    就这么简单,不用再像每个POJO对像上去@JsonSerializer(using...)了。

    以后对所有DATE类型字段序列化JSON,都会默认传为“yyyy-MM-dd HH:mm:ss”格式,对于字段为null的也会转为“”。如果你对null有别的处理。你可以在自定义的NullSerializer修改你想要的格式。

  • 相关阅读:
    反转链表
    链表中倒数第k个结点
    调整数组顺序使奇数位于偶数前面
    词根词缀,非核心prefix/suffix/root
    核心过去式/过去完成时Past tense / past perfect
    非顺序表达
    英语连读
    图片,视频总结
    sql,explain
    @transaction注解
  • 原文地址:https://www.cnblogs.com/wych/p/4193271.html
Copyright © 2020-2023  润新知