Here, the Atrribute method is used to convert a Json string to a C # object. This version is only applicable to Json strings, such as "response": "Hello", "id": 21231513, "result": 100, "msg": "OK. "; instead of a Json array. The atrrikey here is used for attributes. Like Atrribute in NHibernate, it is used for reflection at runtime to obtain the key corresponding to this attribute in the Json string.
Copy codeThe Code is as follows: 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 ;}
}
}
}
Next, the core code in this conversion tool is to parse and analyze the key and value in the Json string, and obtain the corresponding attributes of the object through reflection and assign values.Copy codeThe Code is as follows: 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 });
}
}
}
Finally, this is the code for testing.
Copy codeThe Code is as follows: 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 ;}
}
Copy codeThe Code is as follows: class Program
{
Static void Main (string [] args)
{
JsonToInstance util = new JsonToInstance ();
String json = "\" response \ ": \" I'm a yellow chicken with a cat sauce \ ", \" id \ ": 21231513, \" result \ ": 100, \ "msg \": \ "OK. \"";
Message m = util. ToInstance <Message> (json );
}
}