C # mutual conversion between objects and JSON strings

Source: Internet
Author: User

From: http://hi.baidu.com/lm_lemon/blog/item/af81e8ec08e532252cf534ba.html

 

 

Newtonsoft. Json. dll is required for DoNet2.0.

Code

 Using System;
Using System. IO;
Using System. Text;
Using Newtonsoft. Json;

Namespace OfflineAcceptControl. UCTools
{
Public class JsonTools
{
// Generate a Json string from an object
Public static string ObjectToJson (object obj)
{
Return JavaScriptConvert. SerializeObject (obj );
}
// Generate object information from a Json string
Public static object JsonToObject (string jsonString, object obj)
{
Return JavaScriptConvert. DeserializeObject (jsonString, obj. GetType ());
}
}
}

 

 

 

 

Donet3.5 comes with DLL processing json strings

Note: Reference: System. Runtime. Serialization, System. ServiceModel. Web

Code

 Using System;
Using System. Collections. Generic;
Using System. IO;
Using System. Linq;
Using System. Text;
Using System. Runtime. Serialization;
Using System. Runtime. Serialization. Json;

Namespace CrjIIOfflineAccept. CrjIITools
{
Public class JsonTools
{
// Generate a Json string from an object
Public static string ObjectToJson (object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer (obj. GetType ());
MemoryStream stream = new MemoryStream ();
Serializer. WriteObject (stream, obj );
Byte [] dataBytes = new byte [stream. Length];
Stream. Position = 0;
Stream. Read (dataBytes, 0, (int) stream. Length );
Return Encoding. UTF8.GetString (dataBytes );
}
// Generate object information from a Json string
Public static object JsonToObject (string jsonString, object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer (obj. GetType ());
MemoryStream mStream = new MemoryStream (Encoding. UTF8.GetBytes (jsonString ));
Return serializer. ReadObject (mStream );
}
}
}

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.