Reprinted from http://www.cnblogs.com/vingi/articles/2578659.html
The third-party library is not required to use JSON in C #. You can use the system. runtime. serialization. JSON file that comes with. Net framwork3.5 to parse JSON.
For more information about JSON, see the following figure on the homepage ):
Http://www.json.org/
I. Using
You need to add reference: system. servicemodel. Web and system. runtime. serialization, and then use using
using System.Runtime.Serialization;using System.Runtime.Serialization.Json;
Ii. Define serialized classes
Assume that the JSON string format to be converted is:
{ "encoding":"UTF-8", "plug-ins":["python","c++","ruby"], "indent":{ "length":3, "use_space":true }}
Then write the corresponding serialized class. Pay attention to the attribute added to the following class:
[DataContract(Namespace = "json")] class Config { [DataMember(Order = 0)] public string encoding { get; set; } [DataMember(Order = 1)] public string[] plugins { get; set; } [DataMember(Order = 2)] public Indent indent { get; set; } } [DataContract(Namespace = "json")] class Indent { [DataMember(Order = 0)] public int length { get; set; } [DataMember(Order = 1)] public bool useSpace { get; set; } }
3. convert an object to a JSON string
Use the writeobject method:
Config = new config () {encoding = "UTF-8", plugins = new string [] {"Python", "C ++", "C #"}, indent = new indent () {length = 8, usespace = false }}; datacontractjsonserializer serializer = new datacontractjsonserializer (typeof (config); memorystream stream = new memorystream (); serializer. writeobject (stream, config); // byte [] databytes = new byte [stream. length]; // stream. position = 0; // stream. read (databytes, 0, (INT) stream. length); // string datastring = encoding. utf8.getstring (databytes); // The comments can be replaced by the following sentence, which is simpler than string datastring = encoding. utf8.getstring (stream. toarray (); stream. close (); console. writeline ("JSON string is:"); console. writeline (datastring );
4. convert a JSON string to an object
Use the readobject method:
MemoryStream stream2 = new MemoryStream(Encoding.UTF8.GetBytes(dataString)); DataContractJsonSerializer serializer2 = new DataContractJsonSerializer(typeof(Config)); Config config2 = serializer2.ReadObject(stream2) as Config; stream2.Close(); Console.WriteLine("Encoding is: {0}", config2.encoding); foreach (string plugin in config2.plugins) { Console.WriteLine("plugins is: {0}", plugin); } Console.WriteLine("indent.length is: {0}", config2.indent.length); Console.WriteLine("indent.use_space is: {0}", config2.indent.useSpace);
5. output results: