JSON data is simple in format and useful for data persistence and object transfer. Recently in making a Razor code generator, you need to change the database tables and columns of information to save, think of serializing objects with JSON and save, when needed to deserialize the object will be simpler. CodePlex found the Fastjson project, it seems very good appearance. Here is the performance test that the author does:
Code calls
Copy Code code as follows:
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); Serialization of
var z = fastjson.json.instance.toobject<zoo> (JSON); Deserialization
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;}
}
The basic call is so simple! It is important to note that the class to deserialize seems to have to be declared public.
a quick secret
A general glance at the code shows that the reason for this is that the author emit a lot of IL code using reflection:
Copy Code code as follows:
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);
}
}