Reputation: 103
I want to make a web response object from a service layer object. For the service layer object I have:
public class clothdata
{
public clothname {get;set;}
public Dictionary<string, int> textilenode {get;set;}
}
Which I want to convert to
public class clothdataview
{
[JsonPropertyName("name")]
public clothname {get;set;}
[JsonPropertyName("textile summary")]
public Dictionary<string, string> textilenode {get;set;}
}
The mapper is just converting the type of value in textilenode from integer to string (I will/may convert to other types in the future).
For controller I have written the mapper:
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<clothdata, clothdataview>()
But I don't know how to write the .formember
part
Can you advise ?
Thank you
Upvotes: 1
Views: 183
Reputation: 45119
So, what is the problem?
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 Fiddle: https://dotnetfiddle.net/LcBHGi
Upvotes: 1