开发环境:

一、JSON 转 Object

1.问题:

2.解决方案

二、Object转 JSON

三、SpringBoot设置fastjson2 为默认

pom.xml

2. 配置类

四、FastJson2 注解

默认

2. @JSONType 类注解

3. @JSONField(name = "othername") 属性注解

五、思考问题

Java 对象为什么需要序列化?

为什么对象没有实现Serializable接口,也可以使用Fastjson序列化?


开发环境:

  • Spring cloud

  • Fastjson2

一、JSON 转 Object

  • 推送第三方数据时,对方http接口消息体为json,但是字段首字母大写

  • 我们需要接收JSON 转 Object

[

{

"ItemCode": "WIND_SPEED",

"ItemValue": "2.1",

"WorkTime": "20230104165400",

"Remark": "风速(m/s)"

}

]

  • 返回结果首字母大写:

{"Status": "1","Msg": "服务调用处理成功"}

1.问题:

序列化和反序列化时字段首字母自动变成小写:如


@Data
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class Item {
    private String ItemCode;
    private String ItemValue;
    private String WorkTime;
    private String Remark;
}

@Data
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class RspResult {
    private String Status;
    private String Msg;
}

  • 序列化使用 JSON.toJSONString(Object object),首字母自动变成小写

[

{

"itemCode": "WIND_SPEED",

"itemValue": "2.1",

"workTime": "20230104165400",

"remark": "风速(m/s)"

}

]

  • 反序列化:使用 JSON.parseObject(String text, Class<T> clazz) 转换出对象为null

  • text为 {"Status": "1","Msg": "服务调用处理成功"}

  • clazz 为 {"status": null,"msg": null}

2.解决方案

  • 使用 @JSONField(name = "ItemCode") 或 @JsonProperty("ItemCode")

  • Java代码中元素首字母必须小写,否则@JSONField@JsonProperty失效

如 private String itemCode;

二、Object转 JSON

  • 我们提供接口,返回JSON字段首字母大写

这里SpringBoot默认使用Jackson,所以用 @JsonProperty

@JsonProperty

@JSONField

JSON.toJSONString(Object object)

生效

生效

接口返回Object

生效

不生效

(因为spring boot默认Jackson

三、SpringBoot设置fastjson2 为默认

注意:千万不要在老项目中修改,否则你返回的字段会有问题,如下

字段名

Jackson(无注解)

fastjson2(无注解)

eName

eName(不变

EName

  1. pom.xml

<!-- pom.xml -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <!-- 去掉Jackson依赖,用fastjson -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>


        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.6</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2-extension</artifactId>
            <version>2.0.6</version>
            <!-- <version>${fastjson2.version}</version> -->
        </dependency>

2. 配置类


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.util.ArrayList;
import java.util.List;


@Configuration
public class JsonMessageConverterConfigurer implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        // 自定义配置...
        // FastJsonConfig config = new FastJsonConfig();
        // config.set...
        // converter.setFastJsonConfig(config);

        // spring boot高版本无需配置,低版本不配置报错:Content-Type cannot contain wildcard type '*'
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON);
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        converter.setSupportedMediaTypes(fastMediaTypes);

        converters.add(0,converter);
    }
}

四、FastJson2 注解

  1. 默认

代码

是否返回null字段

JSON.toJSONString(Object)

接口 return Object

JSON.toJSONString(Object,JSONWriter.Feature.WriteMapNullValue)

类注解@JSONType(serializeFeatures = JSONWriter.Feature.WriteMapNullValue)

2. @JSONType 类注解

代码

描述

@JSONType(serializeFeatures = JSONWriter.Feature.WriteMapNullValue)

返回null字段

3. @JSONField(name = "othername") 属性注解

代码

描述

@JSONField(name = "Temperature")

private String temperature;

字段重命名Temperature

注意:属性首字母必须小写否则@JSONField失效

五、思考问题

  1. Java 对象为什么需要序列化?
  1. 为什么对象没有实现Serializable接口,也可以使用Fastjson序列化?

详情请移步 【Spring】1.Java对象序列化和反序列化

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐