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); } }}