Silverlight 使用DataContractJsonSerializer序列化与反序列化 Json

时间:2023-03-08 16:54:32

环境说明:Silverlight 5.1,.Net Framework  ​4.0

1.添加引用System.ServiceModel.Web.dll。

  因为 System.Runtime.Serialization.Json.DataContractJsonSerializer 类的引用是在System.ServiceModel.Web.dll这个程序集中。

2.代码如下

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json; namespace SilverlightApplication2
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
} private void button1_Click(object sender, RoutedEventArgs e)
{
//textBox1.Text = "test button"; List<TestJson> list = new List<TestJson>(){
new TestJson(){ Id=,Name="test1"},
new TestJson(){ Id=,Name="test2"},
new TestJson(){ Id=,Name="test3"},
new TestJson(){ Id=,Name="test4"}
}; string json = JsonHelp.JsonSerializer<List<TestJson>>(list);
MessageBox.Show(json); var result = JsonHelp.JsonDeSerializer<List<TestJson>>(json);
var resultJson = result.FirstOrDefault();
MessageBox.Show(string.Format("id={0},name={1}", resultJson.Id, resultJson.Name));
}
} public class TestJson
{
public int Id { get; set; }
public string Name { get; set; }
} public class JsonHelp
{
/// <summary>
/// json序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static string JsonSerializer<T>(T t) where T : class
{
DataContractJsonSerializer dcs = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream())
{
dcs.WriteObject(ms, t);
byte[] bs = ms.ToArray();
string jsonStr = Encoding.UTF8.GetString(bs, , bs.Length);
return jsonStr;
}
} /// <summary>
/// json反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonStr"></param>
/// <returns></returns>
public static T JsonDeSerializer<T>(string jsonStr) where T : class
{
DataContractJsonSerializer dcs = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr)))
{
return dcs.ReadObject(ms) as T;
}
}
}
}

3.序列化结果

Silverlight 使用DataContractJsonSerializer序列化与反序列化 Json

4.反序列化结果

Silverlight 使用DataContractJsonSerializer序列化与反序列化 Json