json文本怎么转DTO

将JSON文本转换为DTO(Data Transfer Object)通常涉及以下几个步骤:

  1. 定义DTO类:首先,根据JSON结构定义相应的Java类,这些类应包含与JSON字段对应的属性和相应的getter和setter方法。

  2. 使用JSON处理库:使用如Jackson或Gson等JSON处理库来解析JSON文本并将其映射到DTO对象。

  3. 处理嵌套对象和数组:如果JSON中包含嵌套对象或数组,需要在DTO类中定义相应的嵌套类或集合类型。

  4. 考虑日期和时间格式 :如果JSON中包含日期和时间,需要确保DTO类中的相应字段类型为LocalDateTimeLocalDateOffsetDateTime等,并使用适当的格式注解。

  5. 处理可选字段和空值 :使用@Nullable注解或Java 8的Optional类来处理可能为null的字段。

示例

假设有以下JSON文本:

json 复制代码
{
  "id": "310970",
  "name": "营销系统人力资源部",
  "parentId": "311088",
  "departmentLevel": "50",
  "idPath": "/200000/311088/310970/",
  "namePath": "/xxx/人力资源系统/营销系统人力资源部/",
  "levelPath": "/10/30/50/",
  "status": "0",
  "departmentDesc": "L3",
  "departmentCreatedAt": 1527782400000,
  "effectiveDateTime": 1527782400000,
  "leader": "80036462",
  "channel": "CORE_HR",
  "updatedAt": 1692675765000,
  "isEntity": "Y",
  "deptType": "1",
  "setId": "xxx",
  "departmentSeq": "520",
  "nameEn": "NONE(invalid)",
  "nameEnPath": "/xxx/HR System/NONE(invalid)/",
  "departmentDescEn": "",
  "isModel": "",
  "locations": [
    {
      "deptId": "310970",
      "countryCode": "CHN",
      "countryDesc": "中国",
      "countryDescEn": "China",
      "cityCode": "440300",
      "cityDesc": "深圳市",
      "cityDescEn": "",
      "updatedAt": 1672141857000
    }
  ],
  "departmentCreatedAtStr": "2018-06-01 00:00:00",
  "effectiveDateTimeStr": "2018-06-01 00:00:00",
  "updatedAtStr": "2023-08-22 11:42:45"
}

定义DTO类

java 复制代码
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDateTime;
import java.util.List;

public class DepartmentInfoDTO {
    private String id;
    private String name;
    private String parentId;
    private String departmentLevel;
    private String idPath;
    private String namePath;
    private String levelPath;
    private String status;
    private String departmentDesc;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime departmentCreatedAt;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime effectiveDateTime;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updatedAt;
    private String leader;
    private String channel;
    private String isEntity;
    private String deptType;
    private String setId;
    private String departmentSeq;
    private String nameEn;
    private String nameEnPath;
    private String departmentDescEn;
    private String isModel;
    private List<LocationDTO> locations;
    private String departmentCreatedAtStr;
    private String effectiveDateTimeStr;
    private String updatedAtStr;

    // Getters and setters
}

public static class LocationDTO {
    private String deptId;
    private String countryCode;
    private String countryDesc;
    private String countryDescEn;
    private String cityCode;
    private String cityDesc;
    private String cityDescEn;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime updatedAt;

    // Getters and setters
}

使用Jackson解析JSON

java 复制代码
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonToDtoConverter {
    public static void main(String[] args) {
        String jsonText = "{\"id\":\"310970\",\"name\":\"营销系统人力资源部(失效)\",...}"; // 完整的JSON文本

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            DepartmentInfoDTO departmentInfo = objectMapper.readValue(jsonText, DepartmentInfoDTO.class);
            // 现在 departmentInfo 对象包含了JSON数据
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

确保处理任何可能的异常,并根据需要调整DTO类和解析逻辑。如果JSON结构非常复杂或经常变化,考虑使用更灵活的解析策略,例如使用@JsonAnySetter注解或自定义反序列化逻辑。

相关推荐
青衫码上行几秒前
【从零开始学习JVM】程序计数器
java·jvm·学习·面试
不吃香菜学java8 小时前
Redis的java客户端
java·开发语言·spring boot·redis·缓存
captain3768 小时前
事务___
java·数据库·mysql
北漂Zachary9 小时前
四大编程语言终极对比
android·java·php·laravel
小江的记录本9 小时前
【网络安全】《网络安全常见攻击与防御》(附:《六大攻击核心特性横向对比表》)
java·网络·人工智能·后端·python·安全·web安全
嗑嗑嗑瓜子的猫10 小时前
Java!它值得!
java·开发语言
2401_8955213411 小时前
【Spring Security系列】Spring Security 过滤器详解与基于JDBC的认证实现
java·后端·spring
皮卡蛋炒饭.11 小时前
线程的概念和控制
java·开发语言·jvm
一只大袋鼠11 小时前
MyBatis 入门详细实战教程(一):从环境搭建到查询运行
java·开发语言·数据库·mysql·mybatis
程序员老邢11 小时前
【人生底稿・番外篇 05】我的电影江湖:从录像带时代,到港片陪伴的青春岁月
java·程序人生·职场发展·娱乐