Convert any JSON to C # dynamic class. You do not need to declare a C # type first, and convert the JSON string to a dynamic class.
Example:
Class Program
{
Static Void Main ( String [] ARGs)
{
String JSON = " {Name: 'hooyes ', PWD: 'hooyespwd', books: {A: 'Dream of Red Mansions ', B: 'water margin pass', C: {arr: ['baoyu ', 'lin Daiyu '] }}, arr: ['good', 'very good']} " ;
Dynamic DY=Convertjson (JSON );
Console. writeline (dy. Name );
Console. writeline (dy. Books. );
Console. writeline (dy. Arr [1]);
Foreach(VAR sInDy. Books. C. Arr)
{
Console. writeline (s );
}
Console. Read ();
}
Static Dynamic convertjson ( String JSON)
{
Javascriptserializer JSS = New Javascriptserializer ();
JSS. registerconverters ( New Javascriptconverter [] { New Dynamicjsonconverter ()});
Dynamic DY = JSS. deserialize (JSON, Typeof ( Object )) As Dynamic;
Return Dy;
}
}
Two custom classes are used: dynamicjsonconverter and dynamicjsonobject.
Code
Public Class Dynamicjsonconverter: javascriptconverter
{
Public Override Object Deserialize (idictionary < String , Object > Dictionary, type, javascriptserializer serializer)
{
If (Dictionary = Null )
Throw New Argumentnullexception ( " Dictionary " );
If(Type=Typeof(Object))
{
ReturnNewDynamicjsonobject (dictionary );
}
ReturnNull;
}
PublicOverrideIdictionary<String,Object>Serialize (ObjectOBJ, javascriptserializer serializer)
{
ThrowNewNotimplementedexception ();
}
Public Override Ienumerable < Type > Supportedtypes
{
Get { Return New Readonlycollection < Type > ( New List < Type > ( New Type [] { Typeof ( Object )}));}
}
}
Code
Public Class Dynamicjsonobject: dynamicobject
{
Private Idictionary < String , Object > Dictionary { Get ; Set ;}
Public dynamicjsonobject (idictionary string , Object > dictionary)
{< br> This . dictionary = dictionary;
}
PublicOverrideBoolTrygetmember (getmemberbinder binder,OutObjectResult)
{
Result=This. Dictionary [binder. Name];
If (Result Is Idictionary < String , Object > )
{
Result = New Dynamicjsonobject (Result As Idictionary < String , Object > );
}
Else If (Result Is Arraylist && (Result As Arraylist) Is Idictionary < String , Object > )
{
Result = New List < Dynamicjsonobject > (Result As Arraylist). toarray (). Select (x => New Dynamicjsonobject (x As Idictionary < String , Object > )));
}
Else If (Result Is Arraylist)
{
Result = New List < Object > (Result As Arraylist). toarray ());
}
ReturnThis. Dictionary. containskey (Binder. Name );
}
}