C#簡單快速的json組件fastJSON使用介紹

來源:互聯網
上載者:User

JSON資料格式簡潔,用於資料的持久化和對象傳輸很實用。最近在做一個Razor代碼產生器,需要把資料庫的表和列的資訊修改後儲存下來,想到用JSON序列化對象並儲存,需要時再還原序列化成對象會簡單一些。codeplex上發現了fastJSON項目,好像很不錯的樣子。這裡是作者做的效能測試:

代碼調用 複製代碼 代碼如下:namespace test
{

class Program
{
static void Main(string[] args)
{
var zoo1 = new zoo();

zoo1.animals = new List<animal>();
zoo1.animals.Add(new cat() { Name = "hello kitty", legs = 4 });
zoo1.animals.Add(new dog() { Name = "dog1", tail = true });
string json= fastJSON.JSON.Instance.ToJSON(zoo1); //序列化
var z = fastJSON.JSON.Instance.ToObject<zoo>(json); //還原序列化

Console.WriteLine(z.animals[0].Name);
Console.Read();
}
}

public class animal { public string Name { get; set; } }
public class cat : animal { public int legs { get; set; } }
public class dog : animal { public bool tail { get; set; } }
public class zoo { public List<animal> animals { get; set; }
}

基本的調用就是這麼簡單! 需要注意的是要還原序列化的類好像必須聲明為public的。

快速的秘密
大體瀏覽了一下代碼,發現之所以快速的原因是作者利用反射時Emit了大量的IL代碼:

複製代碼 代碼如下:internal object FastCreateInstance(Type objtype)

{
try
{
CreateObject c = null;
if (_constrcache.TryGetValue(objtype, out c))
{
return c();
}
else
{
if (objtype.IsClass)
{
DynamicMethod dynMethod = new DynamicMethod("_", objtype, null);
ILGenerator ilGen = dynMethod.GetILGenerator();
ilGen.Emit(OpCodes.Newobj, objtype.GetConstructor(Type.EmptyTypes));
ilGen.Emit(OpCodes.Ret);
c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
_constrcache.Add(objtype, c);
}
else // structs
{
DynamicMethod dynMethod = new DynamicMethod("_",
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
typeof(object),
null,
objtype, false);
ILGenerator ilGen = dynMethod.GetILGenerator();
var lv = ilGen.DeclareLocal(objtype);
ilGen.Emit(OpCodes.Ldloca_S, lv);
ilGen.Emit(OpCodes.Initobj, objtype);
ilGen.Emit(OpCodes.Ldloc_0);
ilGen.Emit(OpCodes.Box, objtype);
ilGen.Emit(OpCodes.Ret);
c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
_constrcache.Add(objtype, c);
}
return c();
}
}
catch (Exception exc)
{
throw new Exception(string.Format("Failed to fast create instance for type '{0}' from assemebly '{1}'",
objtype.FullName, objtype.AssemblyQualifiedName), exc);
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.