首页 > 解决方案 > 如何将 java 自定义对象转换为字符串并再次返回

问题描述

我想编写一个转换器来将我的自定义对象转换为 DTO 并返回。我该如何处理?

我有 2 个类 Appointment 和 Doctor 这是 Appointment 的一个子类。我希望转换器尽可能简单。我不是在寻找直接的答案,希望获得有关如何处理它的提示。

下面的类有getter和setter:

public class Doctor {

  private long id;

  private String name;

  private String surname;

  private String key;
}

public class Appointment {


  private long id;

  private String description;

  private Doctor doctor;

  private Date appointmentDate;

}


//converter
public class ConverterComponent {
public AppointmentDTO convert(Appointment appointment){
    AppointmentDTO appointmentDTO = new AppointmentDTO();
    appointmentDTO.id = appointment.getId();
    appointmentDTO.description = appointment.getDescription();
    appointmentDTO.doctor = appointment.getDoctor().toString();
    appointmentDTO.appointmentDate = appointment.getAppointmentDate().toString();
    return appointmentDTO;
}
}

我想在 ConverterComponent 中编写另一个 convert(AppointmentDTOointmentDTO) 方法,该方法将返回 Appointment 对象。

是否可以仅通过将 Object 解析为 json 并再次返回来完成?

谢谢,

标签: javaserialization

解决方案


推荐阅读