Custom transformation of Json strings to C # objects

Source: Internet
Author: User

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. [csharp] 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 ;}}} is the core code in this conversion tool, the key and value in the Json string are decomposed and analyzed. Reflection gets the corresponding attributes of the object and assigns values. [Csharp] 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 ). getProp Erties (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 (K EyValuePair <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 [csharp] 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 ;}} www.2cto.com [csharp] 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 );}}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.