C # objects and JSON strings are converted to each other

Source: Internet
Author: User

. Net2.0 need the help of Newtonsoft.Json.dll

Using system;using system.io;using system.text;using newtonsoft.json;namespace offlineacceptcontrol.uctools{    public class Jsontools    {        //Generate JSON string from an object information 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 ());}}}    

. net3.5 above with DLL processing JSON string

Note reference:system.runtime.serialization,system.servicemodel.web

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 {//From an object information generates a JSON string 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) {Data Contractjsonserializer serializer = new DataContractJsonSerializer (obj.           GetType ()); MemoryStream mstream = new MemoryStream (encoding.utf8.gEtbytes (jsonstring)); Return serializer.        ReadObject (Mstream); }    }}

Record them.

C # objects and JSON strings are converted to each other

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.