Fastjson full support DataBind, it's simple-to-use.
Encode
import com.alibaba.fastjson.JSON;Group group = new Group();group.setId(0L);group.setName("admin");User guestUser = new User();guestUser.setId(2L);guestUser.setName("guest");User rootUser = new User();rootUser.setId(3L);rootUser.setName("root");group.addUser(guestUser);group.addUser(rootUser);String jsonString = JSON.toJSONString(group);System.out.println(jsonString);
Output
{"id":0,"name":"admin","users":[{"id":2,"name":"guest"},{"id":3,"name":"root"}]}
Decode
String jsonString = ...;Group group = JSON.parseObject(jsonString, Group.class);
Group.java
public class Group { private Long id; private String name; private List<User> users = new ArrayList<User>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } public void addUser(User user) { users.add(user); }}
User.java
public class User { private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; }}
Https://github.com/alibaba/fastjson/wiki/Samples-DataBind
Last week, to help colleagues see a problem, is to construct a universal query object, which contains a generic object, in the Spring MVC controller layer to be directly converted through requestbody, Spring MVC code is as follows:
Java code
- @RequestMapping ("/testbind")
- @ResponseBody
- Public String testbind (@RequestBody mgquerycondition<testbean> querycondition) {
- System.out.println (querycondition);
- return "Success";
- }
Java code
- Import java.io.Serializable;
- Public class Testbean implements serializable{
- private Integer ID;
- Public Integer getId () {
- return ID;
- }
- public void SetId (Integer id) {
- this.id = ID;
- }
- @Override
- Public String toString () {
- return "Testbean [id=" + ID + "]";
- }
- }
Java code
- Import Com.alibaba.fastjson.JSON;
- Import Com.alibaba.fastjson.JSONObject;
- Import com.alibaba.fastjson.TypeReference;
- Public class Mgquerycondition<t> {
- private T model;
- private Integer PageNo;
- private Integer Pagenum;
- Public T Getmodel () {
- return model;
- }
- public void Setmodel (T model) {
- This.model = model;
- }
- Public Integer Getpageno () {
- return pageno;
- }
- public void Setpageno (Integer pageno) {
- This.pageno = PageNo;
- }
- Public Integer Getpagenum () {
- return pagenum;
- }
- public void Setpagenum (Integer pagenum) {
- this.pagenum = pagenum;
- }
- @Override
- Public String toString () {
- return "mgquerycondition [model=" + model + ", pageno=" + pageno
- + ", pagenum=" + Pagenum + "]";
- }
- }
If we go to debug, we find that the data type inside the mgquerycondition is jsonobject, if the type conversion problem occurs when the Getmodel is called, then I look at the Fastjson document.
For generic types, use TypeReference for parsing with the following code:
Java code
- Public static void Main (string[] args) {
- mgquerycondition<testbean> test = new mgquerycondition<testbean> ();
- Testbean Testbean = new Testbean ();
- Testbean.setid (1);
- Test.setmodel (Testbean);
- Test.setpageno (1);
- Test.setpagenum (1);
- System.out.println (jsonobject.tojsonstring (test));
- String json = "{\" model\ ": {\" id\ ": 1},\" pageno\ ": 1,\" pagenum\ ": 1}";
- <strong>MgQueryCondition<TestBean> clazz = Json.parseobject (JSON,
- New Typereference<mgquerycondition<testbean>> () {});</strong>
- System.out.println (Clazz.getmodel (). GetClass ());
- }
So we can't use the @requestbody, so we should use the most basic KV structure for the reference.
Fastjson Circular Reference problems
What are circular references and duplicate references
Duplicate references: Multiple properties in an object reference the same object at the same time
For example:
Object obj=new Object(); Map<String,Object> map=new HashMap<>(); map.put("1", obj); map.put("2", obj);//引用了同一个对象 System.out.println(JSON.toJSONString(map));
Circular reference: There is a mutual reference between the properties of an object causing a loop that causes a StackOverflow exception
For example:
Map<String,Object> map1=new HashMap<>(); Map<String,Object> map2=new HashMap<>(); map1.put("1",map2);//map1引用了map2 map2.put("1",map1);//map2又引用了map1,导致循环引用 System.out.println(JSON.toJSONString(map1));
Fastjson How to troubleshoot circular references/duplicate references
Fastjson supports circular reference/duplicate references, and is open by default.
* The first example of serialization results in the following output: {"1":{},"2":{"$ref":"$.1"}}
The first object is serialized normally, and the second object is denoted by a reference
* After serialization of the second column, the output is:{"1":{"1":{"$ref":".."}}}
According to the syntax of Fastjson:
Grammar |
Describe |
{"$ref": "\$"} |
Referencing the root object |
{"$ref": "@"} |
Quote yourself |
{"$ref": ".."} |
Reference Parent Object |
{"$ref": ".. /..”} |
References parent objects of parent object |
{"$ref": "\$.members[0].reportto"} |
Path-based references |
It can be concluded that "$.1" represents the first element (obj) that references the root object (map), "..." Represents a reference to a parent object (MAP1).
Turn off circular references/duplicate references
Fastjson by default, the JSON serialization is detected by cyclic reference, thus avoiding the stackoverflow exception. When serialized JSON is transferred to a browser or other language, these JSON parsers do not support circular references, resulting in data loss. You can turn off cyclic reference detection for Fastjson.
Global configuration shutdown
JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.DisableCircularReferenceDetect.getMask();
Non-global shutdown
JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect);
Handling StackOverflowException
When the cyclic reference detection function is turned off, a StackOverflow exception occurs when serializing, which requires the user to handle whether there is a circular reference between the attributes:
You can use annotations on a field or Getter method @JSONField(serialize=false)
to set some fields to not serialize, thus avoiding circular references.
http://blog.csdn.net/helloxiaoyueyue/article/details/51173168
Samples DataBind Fastjson Circular Reference problem