mardi 17 février 2015

Object Transformer

In C#/.NET, what is the best approach to map data-fields(some arbitrary object) you are 'GET'ing from one RESTful end-point/system, and then 'POST'ing it to another RESTful end-point/system(which is already-known). Here is some sample code...



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

Aucun commentaire:

Enregistrer un commentaire