[C# .NET] Auto Mapper 와 JsonProperty 를 이용해 필드 맵핑하기.

박제현·2024년 6월 6일
0

.NET

목록 보기
4/7
post-thumbnail

패키지 설치

Auto Mapper 를 사용하기 위해서 autoMapper 패키지를 추가한다.

Auto Mapper 사용하기

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

코드 설명

  1. MapperConfiguration
    • MapperConfiguration 객체를 생성하여 매핑 설정을 정의합니다. 이 설정은 cfg.CreateMap<ComputerSnake, Computer>() 호출을 통해 이루어집니다.
  2. CreateMap<ComputerSnake, Computer>
    • ComputerSnake 클래스에서 Computer 클래스로의 매핑을 정의합니다.
  3. ForMember
    • 매핑 규칙을 세부적으로 정의합니다. 각 ForMember 호출은 특정 속성에 대한 매핑을 설정합니다.
    • destination => destination.ComputerId : Computer 클래스의 ComputerId 속성에 대해 매핑을 설정합니다.
    • options => options.MapFrom(source => source.computer_id) : ComputerSnake 클래스의 computer_id 속성을 Computer 클래스의 ComputerId 속성으로 매핑합니다.
  4. 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());
            }
	}

코드 설명

  1. JSON 파일 읽기
    • File.ReadAllText 메서드를 사용하여 "ComputersSnake.json" 파일의 내용을 문자열로 읽습니다. 이 파일에는 ComputerSnake 객체들의 JSON 배열이 포함되어 있습니다.
  2. JSON 역직렬화
    • JsonSerializer.Deserialize 메서드를 사용해 JSON 문자열을 IEnumerable<ComputerSnake> 형태로 역질렬화, 즉 ComputerSnake 객체 컬렉션으로 반환한다.
  3. Null 확인 및 맵핑
    • computerSnakeSystem이 널이 아닌 경우, AutoMapper를 사용해 IEnumerable<ComputerSnake>IEnumerable<Computer>로 매핑한다.

JsonProperty 사용하기

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의 차이

By Copilot

AutoMapper와 JsonProperty는 서로 다른 목적을 가진 도구입니다.
AutoMapper는 복잡한 객체 모델을 DTOs나 다른 간단한 객체로 펼치는 모델 투영 시나리오에 초점을 맞춘 도구입니다. 이는 객체와 객체 간의 매핑 전략을 정의하는 데 사용되며, 관례 기반의 일치 알고리즘을 사용하여 소스를 대상 값에 매핑합니다. 예를 들어, DataTable의 열 "C"와 "D"를 JsonProperty 속성을 사용하여 MyClass의 목록으로 변환하는 방법을 구성할 수 있습니다.
장점:

  • 복잡한 객체 모델을 간단한 모델로 펼칠 수 있습니다.
  • 관례 기반의 매핑 알고리즘을 사용하여 코드를 간결하게 유지합니다.
    단점:
  • 매핑 로직이 복잡해질수록 AutoMapper의 사용이 복잡해질 수 있습니다.
  • 매핑 오류가 발생하면 디버깅이 어려울 수 있습니다.

반면에, JsonProperty는 JSON 형식으로 변환할 때 객체의 Key 이름을 설정하는 데 사용됩니다. 이는 객체를 JSON으로 직렬화하거나, 반대로 JSON을 객체로 역직렬화하는 데 사용됩니다.
장점:

  • JSON 키의 이름을 명시적으로 설정할 수 있습니다.
  • JSON과 객체 간의 직렬화 및 역직렬화를 쉽게 처리할 수 있습니다.
    단점:
  • 각 필드를 개별적으로 지정해야 하므로, 네이밍할 필드의 개수가 많을 경우 사용하기 어렵습니다.

따라서, AutoMapper와 JsonProperty는 서로 다른 문제를 해결하기 위해 설계되었으며, 그들의 장단점과 사용 사례는 그들의 설계 목적에 따라 달라집니다. 이 두 도구는 서로 보완적인 관계에 있을 수 있습니다. 예를 들어, AutoMapper를 사용하여 복잡한 객체를 단순화하고, JsonProperty를 사용하여 JSON 직렬화를 수행할 수 있습니다. 이렇게 하면 각 도구의 장점을 최대한 활용할 수 있습니다.

profile
닷넷 새싹

0개의 댓글

관련 채용 정보