Use JSON in C #

Source: Internet
Author: User

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:



 

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.