c# - 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
部分
你能建议吗?
谢谢
解决方案
那么,问题是什么?
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
推荐阅读
- node.js - 如何映射从 mongoDB 获取的字符串数组并在每个帖子中显示一个特定的标题/正文
- javascript - 使用带有 JSON 数据的 Input 组件创建 Cascading 3 Level Select Dropdown
- azure - 为什么 Azure DevOps 不选择具有整数参数的 ARM 部署?
- linux - 在编辑器中重定向 bash 脚本输出而不保存文件
- kubernetes - Azure Kubernetes 服务 - 即使我没有明确设置自动缩放,集群自动缩放器是否也会被触发?
- spring-mvc - 带有 Java 15 依赖项“Spring Web”的 Spring Starter 报告“执行失败”
- python - Python connect 4播放功能
- javascript - 根据chart.js中的计数和过滤器按月和周对数据进行分组
- java - 如何测量单向延迟?
- sas - 删除 SAS 中的重复子字符串