自定義實(shí)現(xiàn)Json字符串向C#對(duì)象轉(zhuǎn)變的方法
這里使用Atrribute的方式實(shí)現(xiàn)了Json字符串向C#對(duì)象的轉(zhuǎn)變。因?yàn)楣δ芫窒蓿税姹局皇轻槍?duì)于Json字符串,如"response":"Hello","id":21231513,"result":100,"msg":"OK."; 而不是Json數(shù)組。這里的Atrribute是作用在屬性上,像NHibernate中的Atrribute一樣,是在運(yùn)行時(shí)通過(guò)反射來(lái)獲取這個(gè)屬性對(duì)應(yīng)于Json字符串中的哪個(gè)key.
namespace JsonMapper
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class JsonFieldAttribute : Attribute
{
private string _Name = string.Empty;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
}
}
接下來(lái)是這個(gè)轉(zhuǎn)換工具中的核心代碼,主要是分解并且分析Json字符串中key與value, 并且通過(guò)反射獲得對(duì)象中的各個(gè)對(duì)應(yīng)屬性并且賦值。
namespace JsonMapper
{
public class JsonToInstance
{
public T ToInstance<T>(string json) where T : new()
{
Dictionary<string, string> dic = new Dictionary<string, string>();
string[] fields = json.Split(',');
for (int i = 0; i < fields.Length; i++ )
{
string[] keyvalue = fields[i].Split(':');
dic.Add(Filter(keyvalue[0]), Filter(keyvalue[1]));
}
PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
T entity = new T();
foreach (PropertyInfo property in properties)
{
object[] propertyAttrs = property.GetCustomAttributes(false);
for (int i = 0; i < propertyAttrs.Length; i++)
{
object propertyAttr = propertyAttrs[i];
if (propertyAttr is JsonFieldAttribute)
{
JsonFieldAttribute jsonFieldAttribute = propertyAttr as JsonFieldAttribute;
foreach (KeyValuePair<string ,string> item in dic)
{
if (item.Key == jsonFieldAttribute.Name)
{
Type t = property.PropertyType;
property.SetValue(entity, ToType(t, item.Value), null);
break;
}
}
}
}
}
return entity;
}
private string Filter(string str)
{
if (!(str.StartsWith("\"") && str.EndsWith("\"")))
{
return str;
}
else
{
return str.Substring(1, str.Length - 2);
}
}
public object ToType(Type type, string value)
{
if (type == typeof(string))
{
return value;
}
MethodInfo parseMethod = null;
foreach (MethodInfo mi in type.GetMethods(BindingFlags.Static
| BindingFlags.Public))
{
if (mi.Name == "Parse" && mi.GetParameters().Length == 1)
{
parseMethod = mi;
break;
}
}
if (parseMethod == null)
{
throw new ArgumentException(string.Format(
"Type: {0} has not Parse static method!", type));
}
return parseMethod.Invoke(null, new object[] { value });
}
}
}
最后這是用于測(cè)試的代碼
public class Message
{
//{ "result": 100, "response": "Who are you?!", "id": 13185569, "msg": "OK." }
[JsonField(Name = "result")]
public int Result { get; set; }
[JsonField(Name = "response")]
public string Response { get; set; }
[JsonField(Name = "id")]
public int Id { get; set; }
[JsonField(Name = "msg")]
public string Msg { get; set; }
}
class Program
{
static void Main(string[] args)
{
JsonToInstance util = new JsonToInstance();
string json = "\"response\":\"我是阿貓醬的小黃雞\",\"id\":21231513,\"result\":100,\"msg\":\"OK.\"";
Message m = util.ToInstance<Message>(json);
}
}
- C#類(lèi)中方法的執(zhí)行順序是什么
- C#類(lèi)繼承中構(gòu)造函數(shù)的執(zhí)行序列示例詳解
- C#類(lèi)的多態(tài)性詳解
- C#類(lèi)中static變量用法分析
- C#類(lèi)的訪問(wèn)修飾符用法分析
- c#類(lèi)的使用示例
- C#類(lèi)中的屬性使用總結(jié)(詳解類(lèi)的屬性)
- C#類(lèi)中屬性與成員變量的使用小結(jié)
- c#對(duì)象初始化順序?qū)嵗治?/a>
- C#對(duì)象為Null模式(Null Object Pattern)實(shí)例教程
- c#對(duì)象反序列化與對(duì)象序列化示例詳解
- C#對(duì)象與XMl文件之間的相互轉(zhuǎn)換
- 關(guān)于C# 類(lèi)和對(duì)象詳情
相關(guān)文章
基于C#?實(shí)現(xiàn)劉謙春晚魔術(shù)(示例代碼)
劉謙春晚魔術(shù)是一個(gè)讓人嘆為觀止的魔術(shù)表演,其中涉及到了數(shù)學(xué)、編程和創(chuàng)意的結(jié)合,看了春晚魔術(shù)的朋友們,是不是好奇春晚劉謙的魔術(shù)是怎么變的,本文分享C#?實(shí)現(xiàn)劉謙春晚魔術(shù)示例代碼,一起看看吧2024-02-02
C#操作SQLite數(shù)據(jù)庫(kù)方法小結(jié)
這篇文章介紹了C#操作SQLite數(shù)據(jù)庫(kù)的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
WPF實(shí)現(xiàn)動(dòng)畫(huà)效果(六)之路徑動(dòng)畫(huà)
這篇文章介紹了WPF實(shí)現(xiàn)動(dòng)畫(huà)效果之路徑動(dòng)畫(huà),文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06

