Recently in writing something, to use the object and JSON to convert each other, summed up the next, there may be errors, there are online things to find, combined with a record here.
Under. NET 2.0, you need to add your own Newtonsoft.Json.dll dynamic-link library
usingSystem;usingSystem.IO;usingSystem.Text;usingNewtonsoft.json;namespaceofflineacceptcontrol.uctools{ Public classJsontools {//generating a JSON string from an object information Public Static stringObjecttojson (Objectobj) { returnjavascriptconvert.serializeobject (obj); } //generating object information from a JSON string Public Static ObjectJsontoobject (stringJsonstring,Objectobj) { returnjavascriptconvert.deserializeobject (jsonstring, obj. GetType ()); } }}
The dynamic link library that comes with the. NET 3.5 can handle JSON strings and need to reference system.runtime.serialization,system.servicemodel.web.
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Text;usingSystem.Runtime.Serialization;usingSystem.Runtime.Serialization.Json;namespacecrjiiofflineaccept.crjiitools{ Public classJsontools {//generating a JSON string from an object information Public Static stringObjecttojson (Objectobj) {DataContractJsonSerializer Serializer=NewDataContractJsonSerializer (obj. GetType ()); MemoryStream Stream=NewMemoryStream (); Serializer. WriteObject (stream, obj); byte[] Databytes =New byte[Stream. Length]; Stream. Position=0; Stream. Read (Databytes,0, (int) stream. Length); returnEncoding.UTF8.GetString (databytes); } //generating object information from a JSON string Public Static ObjectJsontoobject (stringJsonstring,Objectobj) {DataContractJsonSerializer Serializer=NewDataContractJsonSerializer (obj. GetType ()); MemoryStream Mstream=NewMemoryStream (Encoding.UTF8.GetBytes (jsonstring)); returnSerializer. ReadObject (Mstream); } }}
C # objects and JSON strings are converted to each other