首页 > 代码库 > jackson 常见问题
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:\temp\employee.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代码如下:
- public class Student implements Serializable{
- private static final long serialVersionUID = 685922460589405829L;
- private String name;
- private String age;
- /*get set略*/
- }
json字符串如下:
"{\"address\":\"hunan\",\"name\":\"china\",\"age\":\"5000\"}"
这种情况下,使用jackson从string转换为object的时候,会抛出下面异常:
- 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
- "yyyy-MM-dd‘T‘HH:mm:ss.SSSZ"
- "yyyy-MM-dd‘T‘HH:mm:ss.SSS‘Z‘"
- "EEE, dd MMM yyyy HH:mm:ss zzz"
- "yyyy-MM-dd"
当尸实体中存在Date类型,但是json字符串中是字符串类型
只支持以上几种格式否则报错
- /**
- * java日期对象经过Jackson库转换成JSON日期格式化自定义类
- * @author godfox
- * @date 2010-5-3
- */
- public class CustomDateSerializer extends JsonSerializer<Date> {
- @Override
- public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
- SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
- String formattedDate = formatter.format(value);
- jgen.writeString(formattedDate);
- }
- }
然后在你的POJO上找到日期的get方法
Java代码
- @JsonSerialize(using = CustomDateSerializer.class)
- public Date getCreateAt() {
- return createAt;
- }
- @JsonSerialize(using = CustomDateSerializer.class)
- public Date getCreateAt() {
- return createAt;
- }
- //null的JSON序列
- private class NullSerializer extends JsonSerializer<Object> {
- public void serialize(Object value, JsonGenerator jgen,
- SerializerProvider provider) throws IOException,
- JsonProcessingException {
- jgen.writeString("");
- }
- }
在spring的配置文件中定义这个自定义的Mapper
在spring的配置文件中定义这个自定义的Mapper
Xml代码
- <!-- 启动 MVC注解 -->
- <mvc:annotation-driven>
- <mvc:message-converters>
- <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
- <property name="objectMapper" ref="customObjectMapper" />
- </bean>
- </mvc:message-converters>
- </mvc:annotation-driven>
- <!-- 自定义的JSON ObjectMapper -->
- <bean id="customObjectMapper" class="com.xixi.web4j.util.CustomObjectMapper" />
就这么简单,不用再像每个POJO对像上去@JsonSerializer(using...)了。
以后对所有DATE类型字段序列化JSON,都会默认传为“yyyy-MM-dd HH:mm:ss”格式,对于字段为null的也会转为“”。如果你对null有别的处理。你可以在自定义的NullSerializer修改你想要的格式。
jackson 常见问题