首先引入所需要的包
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.IO;
using System.Diagnostics;
using System.Text;
开始代码
namespace Datas
{
public class TransforData
{
public int X { get; set; }
public int Y { get; set; }
public string Z { get; set; }
}
public partial class MainPage : PhoneApplicationPage
{
// 构造函数
public MainPage()
{
InitializeComponent();
TransforData itransforData = new TransforData()
{
X = 50,
Y = 100,
Z = "200"
};
//将c#对象解析成json字符串
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(TransforData));
ser.WriteObject(ms, itransforData);
byte[] data = ms.ToArray();
ms.Close();
string datajson = Encoding.UTF8.GetString(data, 0, data.Length);
Debug.WriteLine(datajson);
//将json字符串解析成c#对象
TransforData transforData = new TransforData();
MemoryStream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(datajson));
DataContractJsonSerializer ser2 = new DataContractJsonSerializer(transforData.GetType());
transforData = ser2.ReadObject(ms2) as TransforData;
ms.Close();
Debug.WriteLine(transforData.Z);
}
}
}