首页 前端知识 JAVA对象、List、Map和JSON之间的相互转换

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

2024-05-10 22:05:39 前端知识 前端哥 292 503 我要收藏

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

    • 1.Java中对象和json互转
    • 2.Java中list和json互转
    • 3.Java中map和json互转
    • 4.定制化配置Java对象和JSON之间的转换
    • 5.map和对象互转

在这里插入图片描述

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);

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

转载请注明出处或者链接地址:https://www.qianduange.cn//article/8121.html
标签
评论
发布的文章
大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!