Samples DataBind Fastjson Circular Reference problem

Source: Internet
Author: User

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
    1. @RequestMapping ("/testbind")
    2. @ResponseBody
    3. Public String testbind (@RequestBody mgquerycondition<testbean> querycondition) {
    4. System.out.println (querycondition);
    5. return "Success";
    6. }
Java code
  1. Import java.io.Serializable;
  2. Public class Testbean implements serializable{
  3. private Integer ID;
  4. Public Integer getId () {
  5. return ID;
  6. }
  7. public void SetId (Integer id) {
  8. this.id = ID;
  9. }
  10. @Override
  11. Public String toString () {
  12. return "Testbean [id=" + ID + "]";
  13. }
  14. }
Java code
  1. Import Com.alibaba.fastjson.JSON;
  2. Import Com.alibaba.fastjson.JSONObject;
  3. Import com.alibaba.fastjson.TypeReference;
  4. Public class Mgquerycondition<t> {
  5. private T model;
  6. private Integer PageNo;
  7. private Integer Pagenum;
  8. Public T Getmodel () {
  9. return model;
  10. }
  11. public void Setmodel (T model) {
  12. This.model = model;
  13. }
  14. Public Integer Getpageno () {
  15. return pageno;
  16. }
  17. public void Setpageno (Integer pageno) {
  18. This.pageno = PageNo;
  19. }
  20. Public Integer Getpagenum () {
  21. return pagenum;
  22. }
  23. public void Setpagenum (Integer pagenum) {
  24. this.pagenum = pagenum;
  25. }
  26. @Override
  27. Public String toString () {
  28. return "mgquerycondition [model=" + model + ", pageno=" + pageno
  29. + ", pagenum=" + Pagenum + "]";
  30. }
  31. }

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
  1. Public static void Main (string[] args) {
  2. mgquerycondition<testbean> test = new mgquerycondition<testbean> ();
  3. Testbean Testbean = new Testbean ();
  4. Testbean.setid (1);
  5. Test.setmodel (Testbean);
  6. Test.setpageno (1);
  7. Test.setpagenum (1);
  8. System.out.println (jsonobject.tojsonstring (test));
  9. String json = "{\" model\ ": {\" id\ ": 1},\" pageno\ ": 1,\" pagenum\ ": 1}";
  10. <strong>MgQueryCondition<TestBean> clazz = Json.parseobject (JSON,
  11. New Typereference<mgquerycondition<testbean>> () {});</strong>
  12. System.out.println (Clazz.getmodel (). GetClass ());
  13. }

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));
    • 1
    • 2
    • 3
    • 4
    • 5

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));
    • 1
    • 2
    • 3
    • 4
    • 5
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

Large-Scale Price Reduction
  • 59% Max. and 23% Avg.
  • Price Reduction for Core Products
  • Price Reduction in Multiple Regions
undefined. /
Connect with us on Discord
  • Secure, anonymous group chat without disturbance
  • Stay updated on campaigns, new products, and more
  • Support for all your questions
undefined. /
Free Tier
  • Start free from ECS to Big Data
  • Get Started in 3 Simple Steps
  • Try ECS t5 1C1G
undefined. /

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.