JAVA对象、List、Map和JSON之间的相互转换

本文详细介绍了Java中对象、List、Map与JSON之间的转换方法,包括使用JSONObject和Jackson库,以及如何通过SpringBeanConfiguration进行定制化配置,如日期时间处理和空值处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

1.Java中对象和json互转

Object obj = new Object();
String objJson = JSONObject.toJSONString(obj);//java对象转json
Object newObj = JSONObject.parseObject(objJson, Object.class);//json转java对象

2.Java中list和json互转

List<Object> list = new ArrayList<>();
String listJson = JSONObject.toJSONString(list);//list转json
List<Object> newList = JSONObject.parseArray(listJson, Object.class);//json转list

3.Java中map和json互转

Map<String, Object> map= new HashMap<>();
String  mapJson = JSONObject.parseObject(map, Map.class);//map转json
Map newMap = JSONObject.toJavaObject(JSONObject.parseObject(mapJson), Map.class);//json转map

4.定制化配置Java对象和JSON之间的转换

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Configuration
public class SpringBeanConfiguration {
    @Bean
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) { // 方法声明
        ObjectMapper objectMapper = builder.createXmlMapper(false).build(); // 创建ObjectMapper对象
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); // 设置序列化时包含非空字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // 设置序列化时包含非null字段
        JavaTimeModule timeModule = new JavaTimeModule(); // 创建JavaTimeModule对象,用于处理Java 8时间类的序列化和反序列化
        timeModule.addDeserializer(LocalDateTime.class, // 添加LocalDateTime的反序列化器,指定日期时间格式
                new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        timeModule.addSerializer(LocalDateTime.class, // 添加LocalDateTime的序列化器,指定日期时间格式
                new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        objectMapper.disable(MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS); // 禁用重复模块注册的特性
        objectMapper.registerModules(timeModule); // 注册JavaTimeModule模块
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 配置在反序列化时忽略未知属性
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); // 配置在序列化时忽略空对象
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); // 配置允许单引号
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); // 配置接受大小写不敏感的属性
        objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); // 配置接受空字符串作为null对象
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() { // 设置空值的序列化器,将null值序列化为空字符串
            @Override
            public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                gen.writeString("");
            }
        });
        return objectMapper; // 返回配置好的ObjectMapper对象
    }
}

5.map和对象互转

 	    Map<String, Object> data = new HashMap<>();
        data.put("code", 1);
        Map<String, Object> result = new HashMap<>();
        result.put("objectKey", "camera-manage/1950 1709709722186.jpg");
        result.put("fileName", "1950 1709709722186jpg");
        result.put("createTime", "2024-03-06 15:22:02");
        data.put("result", result);
//        //方式一:map转对象
//        RestResponse restResponse = BeanUtil.toBeanIgnoreCase(data, RestResponse.class, true);
//        ImageCaptureDto imageCaptureDto = BeanUtil.toBeanIgnoreCase((Map<String, Object>) restResponse.getResult(), ImageCaptureDto.class, true);
//        System.out.println(imageCaptureDto);
//        Map<String, Object> imageCaptureDtoMap = BeanUtil.beanToMap(imageCaptureDto);
//        System.out.println(imageCaptureDtoMap);
        //方式二:map先转json再转对象
        JSONObject jsonObject = JSONUtil.parseObj(data);
        RestResponse restResponse1 = JSONUtil.toBean(jsonObject, RestResponse.class);
        ImageCaptureDto imageCaptureDto1 = JSONUtil.toBean((JSONObject) restResponse1.getResult(), ImageCaptureDto.class);
        System.out.println(imageCaptureDto1);

6.Long类型属性序列化时转为String

后端Long类型属性返回到前端,数值可能会发生变化,原因可能是超过了前端能接收的最大数值,从而导致精度丢失。
基于此现象,后端可以把Long转成String类型给到前台,方案就是在实体类id字段上增加注解。
情况一:如果使用的是fastjson,加上@JSONField(serializeUsing = ToStringSerializer.class)注解。

@JSONField(serializeUsing = ToStringSerializer.class)
private Long id;

情况二:如果使用的是jackson,加上@JsonFormat(shape = JsonFormat.Shape.STRING)注解。

@JsonFormat(shape = JsonFormat.Shape.STRING)
private Long id;

参考文章:
Java-json相关转换,JSONObject与实体类/map互转、List/List<map>和JSONArray互转、获取JSONObject中的key value、字符串String转换等
【JSON转换】String与JSONObject、JSONArray、JAVA对象和List 的相互转换

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

凡间晨光

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

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

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

打赏作者

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

抵扣说明:

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

余额充值