首页 > 解决方案 > Automapper 在字典类值中转换

问题描述

我想从服务层对象创建一个 Web 响应对象。对于服务层对象,我有:

public class clothdata
{
    public clothname {get;set;}
    public Dictionary<string, int> textilenode {get;set;}
}

我想转换成

public class clothdataview
{
    [JsonPropertyName("name")]
    public clothname {get;set;}
    [JsonPropertyName("textile summary")]
    public Dictionary<string, string> textilenode {get;set;}
}

映射器只是将textilenode 中的值类型从整数转换为字符串(我将来会/可能会转换为其他类型)。

对于控制器,我已经编写了映射器:

 var config = new MapperConfiguration(cfg => {
                cfg.CreateMap<clothdata, clothdataview>()

但我不知道如何写这.formember部分

你能建议吗?

谢谢

标签: c#asp.net-core-mvcautomapper

解决方案


那么,问题是什么?

using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
using AutoMapper;

namespace ConsoleApp
{
    public static class Program
    {
        static void Main()
        {
            var config = new MapperConfiguration(cfg => { cfg.CreateMap<clothdata, clothdataview>(); });
            var mapper = config.CreateMapper();

            var source = new clothdata { clothname = "First", textilenode = new Dictionary<string, int> { { "Foo", 1 } } };
            var dest = mapper.Map<clothdataview>(source);

            var json = System.Text.Json.JsonSerializer.Serialize(dest);
            // Output: {"name":"First","textile summary":{"Foo":"1"}}
            Console.WriteLine(json);
        }
    }

    public class clothdata
    {
        public string clothname { get; set; }
        public Dictionary<string, int> textilenode { get; set; }
    }

    public class clothdataview
    {
        [JsonPropertyName("name")]
        public string clothname { get; set; }
        [JsonPropertyName("textile summary")]
        public Dictionary<string, string> textilenode { get; set; }
    }
}

.Net 小提琴:https ://dotnetfiddle.net/LcBHGi


推荐阅读