转换采用微软.net类库中的 JavaScriptSerializer 类来完成。
序列号所用数据模型定义
复制 保存
public class Study
{
public string Name { get; set; }
public int Age { get; set; }
}
将后台模型转换成json字符串的方法有以下几种:
1、直接将数据序列化为json字符串
复制 保存
Study study = new Study() { Name = "你好", Age = 22 };
JavaScriptSerializer serialize = new JavaScriptSerializer();
string result = serialize.Serialize(study);
结果:{"Name":"你好","Age":22}
2、采用匿名对象自定义数据对象的序列化
复制 保存
Study study = new Study() { Name = "你好", Age = 22 };
JavaScriptSerializer serialize = new JavaScriptSerializer();
string result = serialize.Serialize(new { N = study.Name, A = study.Age });
结果:{"N":"你好","A":22}
3、继承JavaScriptConverter类,实现自定义数据对象的序列化
复制 保存
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web.Script.Serialization;
public class StudyJsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type,
JavaScriptSerializer serializer)
{
if (dictionary == null)
return null;
if (type == typeof(Study))
{
Study result = new Study();
result.Name = dictionary["N"] as string;
result.Age = Convert.ToInt32(dictionary["A"]);
return result;
}
return null;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
Study study = obj as Study;
Dictionary<string, object> result = new Dictionary<string, object>();
if (study != null)
{
result.Add("N", study.Name);
result.Add("A", study.Age);
}
return result;
}
public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>() { typeof(Study) }); }
}
}
序列化对象
复制 保存
Study study = new Study() { Name = "你好", Age = 22 };
JavaScriptSerializer serialize = new JavaScriptSerializer();
serialize.RegisterConverters(new List<JavaScriptConverter>() { new StudyJsonConverter() });
string result = serialize.Serialize(study);
结果:{"N":"你好","A":22}
几种结果的比较
第一种序列化的方法最简单,却有问题最大。当后太数据模型发生变化时,就会影响到前台的JavaScript脚本,前台和后台的的连接过于紧密。并且不能对数据模型的属进行压缩。
第二种和第三种可对数据模型的属性进行压缩,并且后台模型发生改变,也不会影响到前台的JavaScript脚本。在应用时根据情况来采用采用不同的方法。