巴拉巴拉
小魔仙

@ResponseBody用fastjson输出fastjson将long转为String输出

js遇到long过长,精度损失,所以改为使用string来传输,但是将long字段改成String的代价太大了,所以直接让fastjson吧long转换成了String

但是@ResponseBody 返回的是Jackson来序列化的,所以要让spring的消息转换器换成fastjson

maven:

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.45</version>
</dependency>

 

1.配置@ResponseBody使用fastjson

<mvc:annotation-driven>
    <!-- 重新设置@RequestMapping中对@ResponseBody以String类型消息转换器的字符集 -->
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <constructor-arg value="UTF-8" />
        </bean>
        <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>text/html;charset=UTF-8</value>
                    <value>application/json</value>
                    <value>application/xml;charset=UTF-8</value>
                </list>
            </property>
            <property name="features">
                <list>
                    <!-- 默认的意思就是不配置这个属性,配置了就不是默认了 -->
                    <!-- 是否输出值为null的字段 ,默认是false-->

                    <value>WriteMapNullValue</value>

                    <value>WriteNullNumberAsZero</value>
                    <value>WriteNullListAsEmpty</value>
                    <value>WriteNullStringAsEmpty</value>
                    <value>WriteNullBooleanAsFalse</value>
                    <value>WriteDateUseDateFormat</value>

                </list>
            </property>
        </bean>
    </mvc:message-converters>

</mvc:annotation-driven>

2.long转string

import java.io.IOException;
import java.lang.reflect.Type;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;

public class LongToStringSerializer implements ObjectSerializer {

    public static final LongToStringSerializer instance = new LongToStringSerializer();

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features)
            throws IOException {
          SerializeWriter out = serializer.out;
            if (object == null) {
                out.writeNull();
                return;
            }
            String strVal = object.toString();
            out.writeString(strVal);
    }
}

@JSONField(serializeUsing = LongToStringSerializer.class)

private long id;

 

赞(1) 打赏
如果文章对你有帮助,欢迎你来评价反馈。AgainFly » @ResponseBody用fastjson输出fastjson将long转为String输出

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  • Q Q(选填)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏