标签:
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访问不到。
java代码如下:
json字符串如下:
"{\"address\":\"hunan\",\"name\":\"china\",\"age\":\"5000\"}"
这种情况下,使用jackson从string转换为object的时候,会抛出下面异常:
意思是说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);
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(); } }
当尸实体中存在Date类型,但是json字符串中是字符串类型
只支持以上几种格式否则报错
然后在你的POJO上找到日期的get方法
在spring的配置文件中定义这个自定义的Mapper
在spring的配置文件中定义这个自定义的Mapper
就这么简单,不用再像每个POJO对像上去@JsonSerializer(using...)了。
以后对所有DATE类型字段序列化JSON,都会默认传为“yyyy-MM-dd HH:mm:ss”格式,对于字段为null的也会转为“”。如果你对null有别的处理。你可以在自定义的NullSerializer修改你想要的格式。
标签:
原文地址:http://www.cnblogs.com/wych/p/4193271.html