Object Transformer/Adapter

Object Transformer/Adapter

在 C#/.NET 中,映射的最佳方法是什么 data-fields(一些任意的 object)你正在从一个 RESTful end-point/system 中“获取” ,然后将其“POST”到另一个 RESTful end-point/system(即 already-known)。这是一些示例代码... Edit-In 这段代码我正在模拟一个 Source object。但实际上,我试图以动态的方式编写它。我能想出的唯一结论是让用户负责提供一个 field-mappings 文件(json 或 xml)来映射源 [=30= 的数据字段](因为他们大概最了解自己的系统)到 well-known 目标系统。 field-mappings 本质上是一个 key-value 对,目标字段用作 'key',source-field 将是 'value'。 Edit-I 将 'Adapter' 添加到标题。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Reflection;
using NSubstitute;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using System.Diagnostics;

namespace ConsAppJsonNet
{
    class Program
    {
        static void Main(string[] args)
       {
        //GET SOURCE OBJECT
        dynamic sourceObjdyn = GetSourceObj();

        //GET FIELD MAPPINGS
        Dictionary<string, string> fieldMappings = GetFieldMappings();

        //NEW UP DESTINATION OBJECT
        DestinationObject destinationObject = new DestinationObject();

        foreach (var fieldMapping in fieldMappings)
        {
            foreach (var prop in destinationObject.GetType().GetProperties())
            {
                if (prop.Name == fieldMapping.Key)
                {
                    prop.SetValue(destinationObject,    sourceObjdyn.GetType().GetProperty(fieldMapping.Value).GetValue(sourceObjdyn));                        
                    break;
                }
            }
        }

        Console.WriteLine(destinationObject);
        //Console.ReadKey();
    }

    static Dictionary<string,string> GetFieldMappings()
    {
        string jsonFieldMappings = @"       
            {
                ""SSN"":""ssn"",      
                ""GEN_ID"":""sysid"",      
                ""BIRTH_DATE"":""dob""      
            }";

        //DESERALIZE FIELD-MAPPINGS
        Dictionary<string, string> fieldMappings =    JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonFieldMappings);

        return fieldMappings;
    }

    private static dynamic GetSourceObj()
    {
        //MOCK A SOURCE OBJECT
        var sourceObj = Substitute.For<ISourceObject>();
        sourceObj.dob.Returns("10/10/20112");
        sourceObj.ssn.Returns("555-66-5555");
        sourceObj.sysid.Returns("9876");

        return sourceObj;
    }

}//end program

public class DestinationObject
{
    //ctor
    public DestinationObject()
    { }

    public string SSN { get; set; }
    public string GEN_ID { get; set; }
    public string BIRTH_DATE { get; set; }

    public override string ToString()
    {
        return string.Format("BIRTH_DATE = {0},\nSSN = {1},\nGEN_ID = {2}",  this.BIRTH_DATE, this.SSN, this.GEN_ID);
    }

}//end class

public interface ISourceObject
{
     string ssn { get; set; }
     string sysid { get; set; }
     string dob { get; set; }
}

}//end namespace

除非你正在使用一些自动映射库,否则最好的方法是简单地编写一个函数:

public SecondApiObject ConvertFirstApiObject(FirstApiObject data)
{
     // return a new object with the fields from the first one
}

如果您有 IEnumerable 个,您可以使用 Select 调用转换操作:

listOfFirstApiObjects.Select(ConvertFirstApiObject);

如果它总是 一个 IEnumerable,您也可以将转换内联为 Select 参数中的 lambda。