---
title: "jackson JSON对象映射出多余字段的bug"
author: "sw1982"
date: "2013-11-25T15:22:04Z"
tags: []
categories: ["编程语言"]
slug: "jackson-json-bug"
draft: false
lastmod: "2013-11-25T15:22:04Z"
id: 1980244
url: "https://sw1982.iteye.com/blog/1980244"
---

调用方法

 

```
		  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的时候，还是要小心的变量命名， 小写开头。**