容器物件轉換
用Json格式交換不同Model的資料,達到資料轉換的效果
泛型
/*方法*/
using Newtonsoft.Json;
public static class TypeData
{
/// <summary>容器物件轉換</summary>
/// <typeparam name="T1">輸入物件格式</typeparam>
/// <typeparam name="T2">輸出物件格式</typeparam>
/// <param name="Data1">輸入物件資訊</param>
/// <returns>T2</returns>
public static T2 objectChange<T1, T2>(T1 Data1)
{
string strjsonData = JsonConvert.SerializeObject(Data1);
var returnData = JsonConvert.DeserializeObject<T2>(strjsonData);
return returnData;
}
}
/*假設物件*/
public class AModel
{
public string aId { get; set; }
public class ListClass
{
public string Id { get; set; }
public string Name { get; set; }
}
public List<ListClass> list { get; set; }
}
public class BModel
{
public string aId { get; set; }
public class ListClass
{
public string Id { get; set; }
public string Name { get; set; }
}
public List<ListClass> list { get; set; }
}
/*使用*/
var returnData = TypeData.objectChange<AModel ,BModel>(InData);
/*如果需要轉換不同的物件名稱可修改*/
using Newtonsoft.Json;
public static class TypeData
{
/// <summary>
/// 容器物件轉換 增加可轉換不同名稱之物件
/// </summary>
/// <typeparam name="T1">輸入物件格式</typeparam>
/// <typeparam name="T2">輸出物件格式</typeparam>
/// <param name="Data1">輸入物件資訊</param>
/// <returns>T2</returns>
public static T2 objectChange<T1, T2>(T1 Data ,string[] original ,string[] modify)
{
string strjsonData = JsonConvert.SerializeObject(Data);
strjsonData = strReplaceData(strjsonData ,original ,modify);
var returnData = JsonConvert.DeserializeObject<T2>(strjsonData);
return returnData;
}
/// <summary>
/// 陣列取代字串
/// </summary>
/// <param name="Data">輸入完整資料</param>
/// <param name="original">原始等待修改資料</param>
/// <param name="modify">需要修改資料</param>
/// <returns></returns>
public static string strReplaceData(string Data ,string[] original ,string[] modify)
{
var returnData = Data;
if (original.Count() == modify.Count())
{
var intCount = original.Count();
for (int i = 0; i < intCount; i++)
{
returnData = returnData.Replace(original[i] ,modify[i]);
}
}
return returnData;
}
}
/*使用*/
string[] original = { "aId" ,"Name" };
string[] modify = { "Cid" ,"Xname" };
returnData = TypeData.objectChange<AModel ,BModel>(returnData01 ,original ,modify);
我只是一棵樹