• setCycleDetectionStrategy 防止自包含


     1 package com.wzw.jsonConfig;
     2 
     3 /**
     4  * @ProjectName: Zwen_Demo
     5  * @Package: com.wzw.jsonConfig
     6  * @ClassName: User
     7  * @Author: WangZunWen
     8  * @Description: ${description}
     9  * @Date: 2020/5/4 17:02
    10  */
    11 public class User {
    12     private String username;
    13     private Integer age;
    14     private  User user = this;
    15     
    16     //get
    17     //set
    18     
    19 }
    20 //错误展示
    21 public class Test1 {
    22     public static void main(String[] args) {
    23         User user = new User();
    24         user.setUsername("userName");
    25         user.setAge(20);
    26         JsonConfig jsonConfig = new JsonConfig();
    27         JSONObject json = JSONObject.fromObject(user);
    28         System.out.println(json);
    29 
    30     }
    31 }
    32 /*
    33 Exception in thread "main" net.sf.json.JSONException: There is a cycle in the hierarchy!
    34     at net.sf.json.util.CycleDetectionStrategy$StrictCycleDetectionStrategy.handleRepeatedReferenceAsObject(CycleDetectionStrategy.java:97)
    35     at net.sf.json.JSONObject._fromBean(JSONObject.java:859)
    36     at net.sf.json.JSONObject.fromObject(JSONObject.java:194)
    37     at net.sf.json.JSONObject._processValue(JSONObject.java:2793)
    38     at net.sf.json.JSONObject._setInternal(JSONObject.java:2817)
    39     at net.sf.json.JSONObject.setValue(JSONObject.java:1527)
    40     at net.sf.json.JSONObject._fromBean(JSONObject.java:946)
    41     at net.sf.json.JSONObject.fromObject(JSONObject.java:194)
    42     at net.sf.json.JSONObject.fromObject(JSONObject.java:156)
    43     at com.wzw.jsonConfig.Test1.main(Test1.java:22)
    44 
    45 Process finished with exit code 1
    46 */
    47 
    48 
    49 
    50 
    51 
    52 public class Test2 {
    53     public static void main(String[] args) {
    54         User user = new User();
    55         user.setUsername("userName");
    56         user.setAge(20);
    57         JsonConfig jsonConfig = new JsonConfig();
    58         jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
    59         JSONObject json = JSONObject.fromObject(user,jsonConfig);
    60         System.out.println(json);
    61 
    62     }
    63 }
    64 /*
    65 {"user":null,"age":20,"username":"userName"}
    66 
    67 Process finished with exit code 0
    68 */
  • 相关阅读:
    java语法基础(总结)
    ZookeeperclientAPI之创建会话(六)
    对A轮的追逐变得越加狂热,当前距离互联网泡沫到底有多近?
    Java集合(一):Java集合概述
    深入了解Cookie(1)------selenium2进行Cookie操作的前奏
    Cocos2d-X开发中国象棋《九》走棋规则
    java中request,application,session三个域及参数简单示例
    在多浏览器使用JS复制内容到剪切板,无需插件
    初学structs2,结果类型简单示例
    使用servletAPI三种方式简单示例
  • 原文地址:https://www.cnblogs.com/Z-wen/p/12827310.html
Copyright © 2020-2023  润新知