Implementation of the conversion of string types to JSON in C #

Source: Internet
Author: User
This article mainly describes the C # implementation of the string type and JSON between the conversion function, involving C # JSON format data construction, transformation-related operations skills, the need for friends can refer to the following

The examples in this article describe the ability of C # to convert between string types and JSON. Share to everyone for your reference, as follows:


Donet2.0 need to add reference//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 ());} Donet3.5 comes with DLL processing JSON string//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 JSON string from an object information public static string Objecttojson (Object obj) {Datacontractjson Serializer 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) {Datacontractjsonseria Lizer serializer = new DataContractJsonSerializer (obj.      GetType ());      MemoryStream mstream = new MemoryStream (Encoding.UTF8.GetBytes (jsonstring)); Return serializer.    ReadObject (Mstream); }  }}
Related Article

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.