`
sw1982
  • 浏览: 503901 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

jackson JSON对象映射出多余字段的bug

阅读更多

 

调用方法

 

		  ObjectMapper mapper = new ObjectMapper();
//		  mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		  try {
			String json = mapper.writeValueAsString(new A());
			System.out.println(json);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

 

 

类:

 

class A implements Serializable{
	public Integer a;
	public Integer B;
	/**
	 * @return the a
	 */
	public Integer getA() {
		return a;
	}
	/**
	 * @param a the a to set
	 */
	public void setA(Integer a) {
		this.a = a;
	}
	/**
	 * @return the b
	 */
	public Integer getB() {
		return B;
	}
	/**
	 * @param b the b to set
	 */
	public void setB(Integer b) {
		B = b;
	}
	
	
}

 

 

产生json串: 可以看出这里多了一个b字段。

 

{"a":null,"B":null,"b":null}

 

 

 

归根溯源的debug了十几层调用(jackson真心复杂过度了),定位到这个地方:

org.codehaus.jackson.map.introspect.POJOPropertiesCollector._addMethods()

 

其原理是反射访问class, 1获取可访问的public字段。2.获取get/set方法,并根据最低级的常理来推断出字段。

 

常理是什么? getField()方法,对应field字段。 这里也就是出现b字段的根源。

 

这框架是springmvc集成的,返回json对象非常方便,所以在定义页面对象po的时候,还是要小心的变量命名, 小写开头。

 

分享到:
评论
1 楼 di1984HIT 2016-07-04  
学习了~~

相关推荐

Global site tag (gtag.js) - Google Analytics