zoukankan      html  css  js  c++  java
  • FastJson禁用循环引用检测

    我们先来看一个例子:

    package com.elong.bms;
    
    import java.io.OutputStream;
    import java.util.HashMap;
    import java.util.Map;
    
    import com.alibaba.fastjson.JSON;
    
    public class Test {
      public static void main(String[] args) {
        Map<String, Student> maps = new HashMap<String, Student>();
        Student s1 = new Student("s1", 16);
    
        maps.put("s1", s1);
        maps.put("s2", s1);
    
        byte[] bytes = JSON.toJSONBytes(maps);
    
        System.out.println(new String(bytes));
      }
    }

    输出:

    {"s1":{"age":16,"name":"s1"},"s2":{"$ref":"$.s1"}}

    可以看到,这个json如果发到前端是无法使用的,幸好FastJson提供了解决办法,我们来看下,解决办法为禁用循环引用检测,代码如下:

    package com.elong.bms;
    
    import java.io.OutputStream;
    import java.util.HashMap;
    import java.util.Map;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.serializer.SerializerFeature;
    
    public class Test {
      public static void main(String[] args) {
        Map<String, Student> maps = new HashMap<String, Student>();
        Student s1 = new Student("s1", 16);
    
        maps.put("s1", s1);
        maps.put("s2", s1);
        
        SerializerFeature feature = SerializerFeature.DisableCircularReferenceDetect;
    
        byte[] bytes = JSON.toJSONBytes(maps,feature);
    
        System.out.println(new String(bytes));
      }
    }
    

    输出如下:

    {"s1":{"age":16,"name":"s1"},"s2":{"age":16,"name":"s1"}}

    问题是如果我们在spring mvc中使用的时候,需要将SerializerFeature注入到MessageConverter里面,FastJsonHttpMessageConverter。
    但是SerializerFeature是一个enum类型的,又是一个array,考虑到大部分人对这个不熟悉,直接上代码了。

       <bean id="jsonConverter"
         class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
          <property name="supportedMediaTypes" value="application/json;charset=UTF-8"/>
          <property name="features">
            <array value-type="com.alibaba.fastjson.serializer.SerializerFeature">
               <value>DisableCircularReferenceDetect</value>
            </array>
          </property>
       </bean>
       <bean id="DisableCircularReferenceDetect" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
          <property name="staticField" value="com.alibaba.fastjson.serializer.SerializerFeature.DisableCircularReferenceDetect"></property>
       </bean>

    转载地址:http://asialee.iteye.com/blog/2101915?utm_source=tuicool&utm_medium=referral

  • 相关阅读:
    hdu1425
    iOS 纯代码跳转到Xib界面和Storyboard界面
    iOS 获取当前app的 App Store 版本号
    iOS 延时方法,定时器。等待一段时间在执行
    iOS获取当前app的名称和版本号及其他信息(持续维护)
    iOS 截取字符串(持续更新)截取、匹配、分隔
    iOS 屏幕大小尺寸,分辨率,代码获取屏幕大小(持续维护添加)
    iOS NSString只保留字符串中的数字
    iOS NSlog打印数据不完全,xcode处理办法
    iOS Xcode 10.3 xib:-1:未能找到或创建描述的执行上下文“<IBCocoaTouchPlatformToolDescript
  • 原文地址:https://www.cnblogs.com/archermeng/p/7537115.html
Copyright © 2011-2022 走看看