I 've been processing JSON data in. Net over the past few days. I 've taken a lot of detours, but I still don't know much about the technology. I finally solved the problem and shared my experience.
In. net4.0 provides a friendly Json processing method. We can easily add the System. runtime. serializaton. json reference, which is used for processing. You can get a good answer by querying MSDN. Note that the System is used. runtime. serializaton. before Json reference, you must add System. serviceModel. web and System. runtime. serializaton. You can view the call relationship between them through Reflector.
Deserialization of JSON data into generic T
1 DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(T));
2 MemoryStream ms = new MemoryStrea(Encoding.Unicode.GetBytes(jsonString));
3 T t = (T)dcjs.ReadObject(ms);
In. in Net 3.5, I found that the information has supported the first method I mentioned above. I have been calling this method for a long time and may be caused by the version of my DLL, no in-depth research was conducted. Search the Internet, find the open source json. net dll,: http://json.codeplex.com/
Json. NET provides many methods for us to use. The flexibility is quite high. Here are two simple examples:
When the deserialization class is exactly the same as the data in json, The DeserializeObject method is the most convenient and fast. Do not use the same type. Otherwise, an error cannot be converted.
Json to a. net object in case of matching
T or= JsonConvert.DeserializeObject<T>(jsonString);
If we need more flexible deserialization methods, we can use Newtonsoft. json. using this method, we can easily control the type of each attribute after deserialization. For more information, see the example in json. NET documentation:
Flexible deserialization
1 string jsonText = @"{
2 ""short"":{
3 ""original"":""http://www.foo.com/"",
4 ""short"":""krehqk"",
5 ""error"":{
6 ""code"":0,
7 ""msg"":""No action taken""}
8 }";
9
10 JObject json = JObject.Parse(jsonText);
11
12 Shortie shortie = new Shortie
13 {
14 Original = (string)json["short"]["original"],
15 Short = (string)json["short"]["short"],
16 Error = new ShortieException
17 {
18 Code = (int)json["short"]["error"]["code"],
19 ErrorMessage = (string)json["short"]["error"]["msg"]
20 }
21 };
22
23 Console.WriteLine(shortie.Original);
24 // http://www.foo.com/
25
26 Console.WriteLine(shortie.Error.ErrorMessage);
27 // No action taken
I am a beginner. I still have many things to learn. What are the mistakes and supplements? I hope you will pay attention to them ~