We also talk about C # Json, from Json strings to class code,

Source: Internet
Author: User

We also talk about C # Json, from Json strings to class code,
Reading directory

 

  

Json conversion object

Since. net 4.0, Microsoft has provided a complete set of solutions for json processing. Here, there is how to convert a json string into a class C # object. In fact, many people know this code and everyone knows it. I will not say much about it, but post the code first.

1. Add reference System. Web. Extensions

2. Test the code.

1 static class Program 2 {3 /// <summary> 4 // main entry point of the Program. 5 // </summary> 6 static void Main () 7 {8 string jsonStr = "{\" name \ ": \" supperlitt \ ", \" age \": 25, \ "likes \": [\ "C # \", \ "asp.net \"]} "; 9 JavaScriptSerializer js = new JavaScriptSerializer (); 10 var model = js. deserialize <TestModel> (jsonStr); 11 12 Console. writeLine (model. name); 13 Console. writeLine (model. age); 14 Console. writeLine (string. join (",", model. likes); 15 16 Console. readLine (); 17} 18 19 public class TestModel20 {21 public string name {get; set;} 22 23 public int age {get; set ;} 24 25 public List <string> likes {get; set;} 26} 27}

Output content:

 

Reverse Thinking

In the code, json Strings need to be processed frequently ). Every time you encounter a json string, most of them need to be parsed and repeat, and you need to define a C # object class. Is there a good solution? You don't have to write code every time. Automatic Generation...

So LZ thought forward and backward, and thought of a Microsoft class library that was previously used, it should be a Com library of Microsoft.

 

Automatically generate C # class from json string

1. I tried Baidu and tried several available classes. So I found

The following code parses a json string and becomes a C # object.

The Microsoft. JScript. dll class library is referenced here.

1 Microsoft.JScript.Vsa.VsaEngine ve = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();2 var m = Microsoft.JScript.Eval.JScriptEvaluate("(" + jsonStr + ")", ve);

2. The m object is actually a JSObject object, which can be further subdivided internally. Therefore, we tested various types of objects and will discuss the source code later. Let's take a look at the test results first.

We randomly find a json string on the web for processing. Of course, json is a little more complicated.

Ps: the code is as follows:

1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. text; 5 using Microsoft. JScript; 6 7 namespace Common 8 {9 /// <summary> 10 // Json string zhuanh 11 /// </summary> 12 public class JsonHelper: IHelper 13 {14 /// <summary> 15 /// do you want to add get set 16 /// </summary> 17 private bool isAddGetSet = false; 18 19 /// <summary> 20 // data set, temporary 21 /// </summary> 22 private Lis T <AutoClass> dataList = new List <AutoClass> (); 23 24 public JsonHelper () 25 {26} 27 28 public JsonHelper (bool isAddGetSet) 29 {30 this. isAddGetSet = isAddGetSet; 31} 32 33 // <summary> 34 // obtain the string format of the class 35 /// </summary> 36 /// <param name = "jsonStr"> </param> 37 // <returns> </returns> 38 public string GetClassString (string jsonStr) 39 {40 Microsoft. JScript. vsa. vsaEngine ve = Microsoft. JScript. Vsa. vsaEngine. createEngine (); 41 var m = Microsoft. JScript. eval. JScriptEvaluate ("(" + jsonStr + ")", ve); 42 43 int index = 0; 44 var result = GetDicType (JSObject) m, ref index ); 45 46 StringBuilder content = new StringBuilder (); 47 foreach (var item in dataList) 48 {49 content. appendFormat ("\ tpublic class {0} \ r \ n", item. CLassName); 50 content. appendLine ("\ t {"); 51 foreach (var model in item. dic) 52 {53 if (isAddGetSet) 54 {55 content. appendFormat ("\ t \ tpublic {0} {1}", model. value, model. key); 56 content. append ("{get; set ;}\ r \ n"); 57} 58 else 59 {60 content. appendFormat ("\ t \ tpublic {0} {1}; \ r \ n", model. value, model. key); 61} 62 63 content. appendLine (); 64} 65 66 content. appendLine ("\ t}"); 67 content. appendLine (); 68} 69 70 return content. toString (); 71} 72 73 // <summary> 74 /// Obtain the type of string to 75 /// </summary> 76 // <param name = "type"> </param> 77 // <returns> </returns> 78 private string GetTypeString (Type type) 79 {80 if (type = typeof (int) 81 {82 return "int"; 83} 84 else if (type = typeof (bool )) 85 {86 return "bool"; 87} 88 else if (type = typeof (Int64) 89 {90 return "long "; 91} 92 else if (type = typeof (string) 93 {94 return "string"; 95} 96 else if (Type = typeof (List <string>) 97 {98 return "List <string>"; 99} 100 else if (type = typeof (List <int> )) 101 {102 return "List <int>"; 103} 104 else105 {106 return "string "; 107} 108} 109 110 // <summary> 111 // obtain the dictionary type 112 // </summary> 113 // <returns> </returns> 114 private string GetDicType (JSObject jsObj, ref int index) 115 {116 AutoClass classInfo = new AutoClass (); 117 118 var model = (Microsoft. JScript. JSObject) (jsObj )). getMembers (System. reflection. bindingFlags. getField); 119 foreach (Microsoft. JScript. JSField item in model) 120 {121 string name = item. name; 122 Type type = item. getValue (item ). getType (); 123 if (type = typeof (ArrayObject) 124 {125 // set 126 string typeName = GetDicListType (ArrayObject) item. getValue (item), ref index); 127 if (! String. isNullOrEmpty (typeName) 128 {129 classInfo. dic. add (name, typeName); 130} 131} 132 else if (type = typeof (JSObject) 133 {134 // single object 135 string typeName = GetDicType (JSObject) item. getValue (item), ref index); 136 if (! String. isNullOrEmpty (typeName) 137 {138 classInfo. dic. add (name, typeName); 139} 140} 141 else142 {143 classInfo. dic. add (name, GetTypeString (type); 144} 145} 146 147 index ++; 148 classInfo. CLassName = "Class" + index; 149 dataList. add (classInfo); 150 return classInfo. CLassName; 151} 152 153 // <summary> 154 // read the set type 155 // </summary> 156 // <param name = "jsArray"> </param> 157 // <param name = "index"> </param> 158 // <returns> </returns> 159 private string GetDicListType (ArrayObject jsArray, ref int index) 160 {161 string name = string. empty; 162 if (int) jsArray. length> 0) 163 {164 var item = jsArray [0]; 165 var type = item. getType (); 166 if (type = typeof (JSObject) 167 {168 name = "List <" + GetDicType (JSObject) item, ref index) + "> "; 169} 170 else171 {172 name = "List <" + GetTypeString (type) + ">"; 173} 174} 175 176 return name; 177} 178} 179 180 182 public class AutoClass181 {183 public string CLassName {get; set;} 184 private Dictionary <string, string> dic = new Dictionary <string, string> (); 185 186 public Dictionary <string, string> Dic187 {188 get189 {190 return this. dic; 191} 192 set193 {194 this. dic = value; 195} 196} 197} 198}View Code

Call method:

1 JsonHelper helper = new JsonHelper (true); 2 try3 {4 this.txt OutPut. text = helper. getClassString ("json string"); 5} 6 catch7 {8 this.txt OutPut. text = "the input content does not comply with the specifications... "; 9}

 

Finally, if dudu permits it, I will attach another test address: http://www.51debug.com/tool/JsonToCharpCode.aspx.

 

I wrote my blog several times, but I wrote a lot about it every time and it looked uncomfortable. I wrote it with my heart. You are welcome to make a brick or provide better suggestions.

 

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.