Newtonsoft.Json.dll deserialization of Json strings

Source: Internet
Author: User

JSON has been briefly described in the JSON entry-level learning summary--json data structure, JSON string array data styles are probably like this:

Today, because of project requirements (ASP. NET Web site, the foreground passes JSON data to the background, and the JSON is processed in detail, see the blog

Project Experience--get foreground data through JS Pass JSON data to a generic handler and parse JSON data to write JSON data from the foreground to the database table

"), you need to deserialize the JSON data that is passed. So I found many examples of JSON deserialization from the Internet, finally decided to use Newtonsoft.Json.dll to deserialize the JSON string, of course it can also serialize JSON string,Newtonsoft.Json.dll download link !

to deserialize a Json string using Newtonsoft.Json.dll:

1. Adding references to Newtonsoft.Json.dll

Copy the Newtonsoft.Json.dll file to the bin directory of the interface layer, then right-click on the bin, pop up the "Add Reference" page, then click "Browse", then find the Bin folder of the interface layer, locate the Newtonsoft.Json.dll file, then click "Add" , the reference was added successfully!

 

2. In the interface that requires JSON string processing, reference the JSON space and process the JSON

The online solution is roughly as follows:

Method 1:

[CSharp]View PlainCopyprint?
  1. <span style="FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >//Referencing the space used by JSON parsing
  2. Using Newtonsoft.json;
  3. Using System.Text;
  4. Defines a variable string array
  5. StringBuilder sb = new StringBuilder ();
  6. Defines a JSON string str
  7. String str = "[{ID: ' 1 ', Name: ' John ', other:[{age: ' + ', Sex: ' 0 '}]},{id: ' 2 ', ' Name: ' Good ', Other:[{age: ' $ ', Sex: ' 1 '}]  }]";
  8. Deserialization of JSON data
  9. Javascriptarray JavaScript = (javascriptarray) javascriptconvert.deserializeobject (str);
  10. Reads the deserialized JSON data sequentially and writes the data to the variable string array
  11. for (int i = 0; i < JavaScript. Count; i++)
  12. {
  13. //  
  14. Javascriptobject obj = (javascriptobject) javascript[i];
  15. //variable string array add data
  16. Sb. Append ("ID:" + obj["id"].  ToString ());
  17. Sb. Append ("Name:" + obj["name"].  ToString ());
  18. //deserialization of JSON data
  19. Javascriptarray json = (javascriptarray) obj["Other"];
  20. reads the deserialized JSON data sequentially and writes the data to the variable string array
  21. For (int j = 0; J < JSON. Count; J + +)
  22. {
  23. Javascriptobject jsonobj = (javascriptobject) json[j];
  24. Sb. Append ("Age:" + jsonobj["age"].  ToString ());
  25. Sb. Append ("Sex:" + jsonobj["Sex"].  ToString ());
  26. }
  27. } </span>


Another way is to:

[CSharp]View PlainCopy print?
  1. Defines a JSON string str
  2. String jsontext = "[{' A ': ' AAA ', ' B ': ' BBB ', ' C ': ' CCC '},{' a ': ' Aaa2 ', ' B ': ' Bbb2 ', ' C ': ' CCC2 '}]";
  3. //deserialization of JSON data
  4. Jsonreader reader = new Jsonreader (new StringReader (Jsontext));
  5. //Read the deserialized JSON data sequentially
  6. While (reader. Read ())
  7. {
  8. TextBox1.Text + = "Tokentype =" + Reader. Tokentype + "ValueType =" + Reader. ValueType + "Value =" + Reader.    Value + "\ r \ n";
  9. }

The first method compiles direct error, does not recognize Javascriptarray,javascriptobject, even Javascriptconvert method also wood has! Well, the second kind of head office, the hint:

Error 2 Cannot create an instance of an abstract class or interface "Newtonsoft.Json.JsonReader"

What's going on???

Later in the search of the article, found that the new version of Javascriptarray into Jarray, along this line of thought, found the following changes:

[CSharp]View PlainCopyprint?
    1. <span style="FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >javascriptarray--->jarray
    2. Javascriptconvert--->jsonconvert
    3. Javascriptobject--->JObject</span>

In fact, such changes are more standardized!

Here's how to deserialize a Json string in a new version of Newtonsoft.Json.dll

1. Direct deserialization of JSON strings

[CSharp]View PlainCopyprint?
  1. Reference to the space used to serialize, deserialize JSON strings
  2. Using Newtonsoft.json;
  3. Using Newtonsoft.Json.Linq;
  4. //define a JSON string
  5. String jsontext = "[{' A ': ' AAA ', ' B ': ' BBB ', ' C ': ' CCC '},{' a ': ' Aaa2 ', ' B ': ' Bbb2 ', ' C ': ' CCC2 '}]";
  6. Deserializing JSON strings
  7. Jarray ja = (jarray) jsonconvert.deserializeobject (Jsontext);
  8. //Converts a deserialized JSON string into an object
  9. Jobject o = (jobject) ja[1];
  10. Reading the values in an object
  11. Console.WriteLine (o["a"]);
  12. Console.WriteLine (ja[1]["a"]);

2. Define a list of objects and deserialize the JSON string

2.1 Add a class that defines an object

[CSharp]View PlainCopyprint?
  1. Using System;
  2. Using System.Collections.Generic;
  3. Using System.Linq;
  4. Using System.Web;
  5. <summary>
  6. Summary description of Customer
  7. </summary>
  8. Public class Customer
  9. {
  10. //No changes before and after serialization
  11. public string a
  12. { get;  set;}
  13. //Set and reset before and after serialization
  14. public string B
  15. { get;  set;}
  16. //set to NULL, but populated after serialization
  17. public string C
  18. { get;  set;}
  19. public string Other
  20. { get;  set;}
  21. Public Customer ()
  22. {
  23. //    
  24. //todo: Add constructor logic here
  25. //    
  26. A = "";
  27. b = "";
  28. c = "";
  29. other = null;
  30. }
  31. }

2.2 Deserializing JSON strings

[CSharp]View PlainCopyprint?
  1. Reference to the space used to serialize, deserialize JSON strings
  2. Using Newtonsoft.json;
  3. Using Newtonsoft.Json.Linq;
  4. Define a JSON string
  5. String jsontext = "[{' A ': ' AAA ', ' B ': ' BBB ', ' C ': ' CCC '},{' a ': ' Aaa2 ', ' B ': ' Bbb2 ', ' C ': ' CCC2 '}]";
  6. Deserializes a JSON string into a list of JSON strings
  7. list<customer> _list = jsonconvert.deserializeobject<list<customer>> (JsonText);
  8. Reading a value from a list
  9. Console.WriteLine (_LIST[1].A);
  10. foreach (Customer C in _list)
  11. {
  12. Console.WriteLine (C.C);
  13. }


I feel that the two methods of deserializing JSON are very good, in fact, there are many ways to deserialize JSON, this article only with the help of Newtonsoft.Json.dll this tool!

Newtonsoft.Json.dll deserialization of Json strings

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.