spring 不一样的整合fastjson


1、🔥什么是fastjson

fastjson是阿里巴巴开发的一个高性能的Java JSON处理库,它支持将Java对象转换成JSON格式,同时也支持将JSON字符串解析成Java对象。

2、🔥pom.xml 配置

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
   <exclusions>
       <exclusion>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-json</artifactId>
       </exclusion>
   </exclusions>
</dependency>
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.79</version>
</dependency>

3、🔥全局WebMvcConfig配置

package com.gis.fastjson.config;
 

import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        //custom configuration
        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setReaderFeatures(JSONReader.Feature.FieldBased, JSONReader.Feature.SupportArrayToBean);
        config.setWriterFeatures(JSONWriter.Feature.WriteMapNullValue, JSONWriter.Feature.PrettyFormat);
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(StandardCharsets.UTF_8);
       converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
        converters.add(0, converter);
    }
 
}

4、🔥controller测试

package com.gis.fastjson.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class HelloWorldController {
    @RequestMapping("/test")
    public Map<String, Object> showHelloWorld(){
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "Hello World!");
        return map;
    }
}

5、🔥闭坑指南

BigDecimal精度丢失


  @Test
    public void toJSONString() throws ParseException {
        BookDTO  book =  new BookDTO();
        BigDecimal money = new BigDecimal(-40090.07d);
        money = book.setScale(4, RoundingMode.HALF_UP);
        book.setMoney(money);

        String createtime ="2024-07-22 09:03:26.968";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date date = format.parse(createtime);
        book.setCreateTime(date);

        List<BookDTO> list = new ArrayList<>();
        list.add(book);
        String json =J SON.toJSONString(list);
        System.out.println(json);
        // 解决方法
		// String json = JSON.toJSONString(list,  JSONWriter.Feature.WriteBigDecimalAsPlain);
    }
}

日期解析问题

@Test
public void parseArray()  {
    String json="[{\"create_time\":\"2024-07-22 10:03:26.968\",\"money\":-40090.0700}]";
    System.out.println(json);
    List<BookDTO> list1 = JSON.parseArray(json, BookDTO.class,JSONReader.Feature.SupportSmartMatch);
    System.out.println();
}

运行结果
java.time.format.DateTimeParseException: Text ‘2024-07-22 10:03:26.968’ could not be parsed, unparsed text found at index 10

解决方法
BookDTO上加上@JSONField(format= “yyyy-MM-dd HH:mm:ss”)
在这里插入图片描述

要在Spring Boot中整合Fastjson需要进行以下步骤: 1.添加Fastjson依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency> ``` 2.配置FastjsonHttpMessageConverter 在Spring Boot中我们可以使用`@Configuration`和`@Bean`注解来配置`FastjsonHttpMessageConverter`,并将其添加到`HttpMessageConverters`中。 ```java @Configuration public class FastjsonConfig { @Bean public HttpMessageConverters fastjsonHttpMessageConverter() { //定义一个converters转换消息的对象 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); //添加fastjson的配置信息,比如:是否要格式化返回的json数据 FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //在converter中添加配置信息 fastConverter.setFastJsonConfig(fastJsonConfig); HttpMessageConverter<?> converter = fastConverter; return new HttpMessageConverters(converter); } } ``` 3.测试 在Controller中使用`@RestController`注解,并返回一个Object对象。Fastjson会自动将其转换为JSON格式。 ```java @RestController public class UserController { @GetMapping("/user") public Object getUser() { User user = new User(); user.setId(1L); user.setUsername("test"); user.setPassword("123456"); return user; } } ``` 访问http://localhost:8080/user,可以看到返回的JSON格式数据。
评论 31
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gis分享者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值