The conversion between the following objects and json strings is tested in framework2.0 and passed
Note: You need to download Newtonsoft. Json. dll and reference it to the project.
Using System;
Using System. IO;
Using System. Text;
Using Newtonsoft. Json;
NamespaceOfflineAcceptControl. UCTools
{
Publicclass JsonTools
{
// Generate a Json string from an object
Publicstatic stringObjectToJson (objectobj)
{
ReturnJavaScriptConvert. SerializeObject (obj );
}
// Generate object information from a Json string
Publicstatic objectJsonToObject (stringjsonString, objectobj)
{
ReturnJavaScriptConvert. DeserializeObject (jsonString, obj. GetType ());
}
}
}
The conversion between the following objects and json strings is tested in framework3.5
Note: 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
{
Publicclass JsonTools
{
// Generate a Json string from an object
Publicstatic stringObjectToJson (objectobj)
{
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 );
ReturnEncoding. UTF8.GetString (dataBytes );
}
// Generate object information from a Json string
Publicstatic objectJsonToObject (stringjsonString, objectobj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer (obj. GetType ());
MemoryStream mStream = new MemoryStream (Encoding. UTF8.GetBytes (jsonString ));
Returnserializer. ReadObject (mStream );
}
}
}
From SYZ_YUMEIZHOU_YY