下面的對象與json串之間的轉換在framework2.0下測試通過
注意:需要下載 Newtonsoft.Json.dll,並引用到項目中
using System;
using System.IO;
using System.Text;
using Newtonsoft.Json;
namespaceOfflineAcceptControl.UCTools
{
publicclass JsonTools
{
// 從一個對象信息生成Json串
publicstatic stringObjectToJson(objectobj)
{
returnJavaScriptConvert.SerializeObject(obj);
}
// 從一個Json串生成對象信息
publicstatic objectJsonToObject(stringjsonString, objectobj)
{
returnJavaScriptConvert.DeserializeObject(jsonString, obj.GetType());
}
}
}
下面的對象與json串之間的轉換在framework3.5下測試通過
注意引用: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
{
// 從一個對象信息生成Json串
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);
}
// 從一個Json串生成對象信息
publicstatic objectJsonToObject(stringjsonString, objectobj)
{
DataContractJsonSerializer serializer =new DataContractJsonSerializer(obj.GetType());
MemoryStream mStream =new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
returnserializer.ReadObject(mStream);
}
}
}
摘自 SYZ_YUMEIZHOU_YY