jackson反序列化对象

Jackson解析json字符串是区分大小写的,如果对应的字段首字母为大写或者不好设置对应的类型,写出的get方法是获取不到json值的,那么这时候就需要添加@JsonProperty("name")注解来标注反序列化的是哪个字段。

如果反序列化的对象中包含对象或者集合,比如说Map,List等,这时候就需要自定义反序列化程序,代码如下所示:

// 对象get方法
Class<?> retType = method.getReturnType(); 
// 是集合对象
if ( Collection.class.isAssignableFrom(retType) )
	{
	Type genRetType = method.getGenericReturnType();
	ParameterizedType pType = (ParameterizedType)genRetType;
	Class<?> pTypeClazz = (Class<?>) pType.getActualTypeArguments()[0];
	Object childPojo = objectMapper.convertValue(rowMap,pTypeClazz);

	try
		{
		Collection<Object> vals = (Collection<Object>) method.invoke(pojo);
		vals.add(childPojo);
		}
	catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex)
		{
		throw new IllegalStateException("Unable to invoke method annotated with" + idMethod );
		}
	
	}

猜你喜欢

转载自xielongemail.iteye.com/blog/2301963