In Java Json serialization, can not be ignored getter
To reproduce the problem
public class AjaxJson {
private boolean success; private String msg; private Object obj; private Map<String, Object> attributes; //getter and setter public String getJsonStr() { JSONObject obj = new JSONObject(); obj.put("success", this.isSuccess()); obj.put("msg", this.getMsg()); obj.put("obj", this.obj); obj.put("attributes", this.attributes); return obj.toJSONString(); } }
The above is an interface class, we need to target sequences of this class into json return. Then springmvc in general it is operated.
@RequestMapping(params = "/get")
@ResponseBody
public AjaxJson del(HttpServletRequest request) { AjaxJson json = new AjaxJson(); //省略业务操作 return json; }
By default, it returns ResponseBody
the object directly serialize json. This time, we can look at the json returned.
{
"success": "true",
"Msg":"1", "obj":{ ... }, "attributes": null, "jsonStr":"{"success": "true","Msg":"1","obj":{...},"attributes": null,}" }
Obviously, we expect and want is not the same, one more jsonstr field. This time I was thinking, is not springmvc problem. The results carefully think about, springnvc reason can directly serialize an object into json, in fact, we add profile at work, real work is involved in serialization jackson this library. So, I use the jackson alone, and the results returned json string is the same as before, under which it can be sure that the design of the library itself, the jackson.
discuss in depth
With this curiosity, I put java commonly used in json serialization libraries have tried to see if all this. The main library has jackson, fastjson and gson.
After the test found, json string jackson and Ali returned fastjson are presented with a jsonstr field, with the exception of gson google returns the results we expected - only serialized object field.
So I found a series of principles at these libraries:
- jackson fastjson and
in the sequence of the time, first of all found by the reflection method get object classes , to get the next, and of the lower case, as each key value json, and get the return value as the value. Next, the re-reflection Field , added to the json. - gson
did not find popular argument, but it feels it should getter methods and has nothing to do.
So, you can see there is a big getJsonStr our AjaxJson class, therefore, jsonStr it as a key, in a serialized to json.
Of course, jackson, provided the appropriate annotation, such methods can be ignored. In the former method plus @JsonIgnore
you can.
Personal understanding
- When experiencing problems, do not overlook some simple places, such as getter and setter methods. With getXXX place, you can use alternatives such as fetch.
- Sometimes we defined in the class such as
private int mAge
variables and methods getter isgetAge()
. Obviously we hope that in the sequence of time to get the key to age rather than mAge, then the reflection getter method also has a meaning of its existence.