Auto Mapper
를 사용하기 위해서 autoMapper
패키지를 추가한다.
// Class : Computer
public class Computer{
public int ComputerId { get; set; }
public string Motherboard { get; set; }
public int? CPUCores { get; set; }
public bool HasWifi { get; set; }
public bool HasLTE { get; set; }
public DateTime? ReleaseDate { get; set; }
public decimal Price { get; set; }
public string VideoCard { get; set; }
}
// Class : ComputerSnake
public class ComputerSnake
{
public int computer_id { get; set; }
public string motherboard { get; set; }
public int? cpu_cores { get; set; }
public bool has_wifi { get; set; }
public bool has_lte { get; set; }
public DateTime? release_date { get; set; }
public decimal price { get; set; }
public string video_card { get; set; }
}
카멜 케이스로 작성된 Computers.json
데이터와 스네이크 케이스로 작성된 ComputersSnake.json
데이터를 매핑 시킨다.
using AutoMapper;
Mapper mapper = new Mapper(new MapperConfiguration(cfg =>
cfg.CreateMap<ComputerSnake, Computer>().ForMember(destination => destination.ComputerId,
options => options.MapFrom(source => source.computer_id))
.ForMember(destination => destination.Motherboard,
options => options.MapFrom(source => source.motherboard))
.ForMember(destination => destination.VideoCard,
options => options.MapFrom(source => source.video_card))
.ForMember(destination => destination.Price, options => options.MapFrom(source => source.price))
.ForMember(destination => destination.HasWifi,
options => options.MapFrom(source => source.has_wifi))
.ForMember(destination => destination.HasLTE,
options => options.MapFrom(source => source.has_lte))
.ForMember(destination => destination.CPUCores,
options => options.MapFrom(source => source.cpu_cores))));
코드 설명
- MapperConfiguration
MapperConfiguration
객체를 생성하여 매핑 설정을 정의합니다. 이 설정은cfg.CreateMap<ComputerSnake, Computer>()
호출을 통해 이루어집니다.- CreateMap<ComputerSnake, Computer>
ComputerSnake
클래스에서Computer
클래스로의 매핑을 정의합니다.- ForMember
- 매핑 규칙을 세부적으로 정의합니다. 각
ForMember
호출은 특정 속성에 대한 매핑을 설정합니다.destination => destination.ComputerId
:Computer
클래스의ComputerId
속성에 대해 매핑을 설정합니다.options => options.MapFrom(source => source.computer_id)
:ComputerSnake
클래스의computer_id
속성을Computer
클래스의ComputerId
속성으로 매핑합니다.- MapFrom
- 매핑 소스 속성을 지정합니다.
ComputerSnake
클래스의 각 속성을Computer
클래스의 대응하는 속성에 매핑합니다.
각각의 필드에 맞게 수동으로 1대1로 매핑해준다.
이 후, ComputersSnake.json
데이터로부터 mapper
를 이용하여 Computer
객체를 생성할 수 있다.
string computerSnakesJson = File.ReadAllText("ComputersSnake.json");
IEnumerable<ComputerSnake>? computerSnakesSystem = JsonSerializer.Deserialize<IEnumerable<ComputerSnake>>(computerSnakesJson);
if (computerSnakesSystem != null)
{
IEnumerable<Computer> computerResult = mapper.Map<IEnumerable<Computer>>(computerSnakesSystem);
foreach (Computer computer in computerResult)
{
Console.WriteLine(computer.ToString());
}
}
코드 설명
- JSON 파일 읽기
File.ReadAllText
메서드를 사용하여 "ComputersSnake.json" 파일의 내용을 문자열로 읽습니다. 이 파일에는ComputerSnake
객체들의 JSON 배열이 포함되어 있습니다.- JSON 역직렬화
JsonSerializer.Deserialize
메서드를 사용해 JSON 문자열을IEnumerable<ComputerSnake>
형태로 역질렬화, 즉ComputerSnake
객체 컬렉션으로 반환한다.- Null 확인 및 맵핑
computerSnakeSystem
이 널이 아닌 경우, AutoMapper를 사용해IEnumerable<ComputerSnake>
를IEnumerable<Computer>
로 매핑한다.
public class Computer{
[JsonPropertyName("computer_id")]
public int ComputerId { get; set; }
[JsonPropertyName("motherboard")]
public string Motherboard { get; set; }
[JsonPropertyName("cpu_cores")]
public int? CPUCores { get; set; }
[JsonPropertyName("has_wifi")]
public bool HasWifi { get; set; }
[JsonPropertyName("has_lte")]
public bool HasLTE { get; set; }
[JsonPropertyName("release_date")]
public DateTime? ReleaseDate { get; set; }
[JsonPropertyName("price")]
public decimal Price { get; set; }
[JsonPropertyName("video_card")]
public string VideoCard { get; set; }
}
[JsonPropertyName("computer_id")]
를 필드 상단에 명시해 줌으로써, 매핑을 가능하게 만든다.
IEnumerable<Computer>? computersJsonPropertyMapping = JsonSerializer.Deserialize<IEnumerable<Computer>>(computerSnakesJson);
if (computersJsonPropertyMapping != null)
{
foreach (Computer computer in computersJsonPropertyMapping)
{
Console.WriteLine(computer.ToString());
}
}
AutoMapper 가 필요 없으며, 이미 매핑이 되어있기 때문에, 바로 Computer
객체로 역직렬화가 가능하다.
AutoMapper와 JsonProperty는 서로 다른 목적을 가진 도구입니다.
AutoMapper는 복잡한 객체 모델을 DTOs나 다른 간단한 객체로 펼치는 모델 투영 시나리오에 초점을 맞춘 도구입니다. 이는 객체와 객체 간의 매핑 전략을 정의하는 데 사용되며, 관례 기반의 일치 알고리즘을 사용하여 소스를 대상 값에 매핑합니다. 예를 들어, DataTable의 열 "C"와 "D"를 JsonProperty 속성을 사용하여 MyClass의 목록으로 변환하는 방법을 구성할 수 있습니다.
장점:
반면에, JsonProperty는 JSON 형식으로 변환할 때 객체의 Key 이름을 설정하는 데 사용됩니다. 이는 객체를 JSON으로 직렬화하거나, 반대로 JSON을 객체로 역직렬화하는 데 사용됩니다.
장점:
따라서, AutoMapper와 JsonProperty는 서로 다른 문제를 해결하기 위해 설계되었으며, 그들의 장단점과 사용 사례는 그들의 설계 목적에 따라 달라집니다. 이 두 도구는 서로 보완적인 관계에 있을 수 있습니다. 예를 들어, AutoMapper를 사용하여 복잡한 객체를 단순화하고, JsonProperty를 사용하여 JSON 직렬화를 수행할 수 있습니다. 이렇게 하면 각 도구의 장점을 최대한 활용할 수 있습니다.