栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

仅使用json序列化对象的一部分

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

仅使用json序列化对象的一部分

// simple dummy object just showing what "MyObject" could potentially bepublic class MyObject{    public String Property1;    public String Property2;    public String Property3;    public String Property4;    public String Property5;    public String Property6;}// custom converter that tells the serializer what to do when it sees one of// the "MyObject" types. Use our custom method instead of reflection and just// dumping properties.public class MyObjectConverter : JavascriptConverter{    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavascriptSerializer serializer)    {        throw new ApplicationException("Serializable only");    }    public override IDictionary<string, object> Serialize(object obj, JavascriptSerializer serializer)    {        // create a variable we can push the serailized results to        Dictionary<string, object> result = new Dictionary<string, object>();        // grab the instance of the object        MyObject myobj = obj as MyObject;        if (myobj != null)        { // only serailize the properties we want result.Add("Property1", myobj.Property1); result.Add("Property3", myobj.Property3); result.Add("Property5", myobj.Property5);        }        // return those results        return result;    }    public override IEnumerable<Type> SupportedTypes    {        // let the serializer know we can accept your "MyObject" type.        get { return new Type[] { typeof(MyObject) }; }    }}

然后在哪里进行序列化:

// create an instance of the serializerJavascriptSerializer serializer = new JavascriptSerializer();// register our new converter so the serializer knows how to handle our custom objectserializer.RegisterConverters(new JavascriptConverter[] { new MyObjectConverter() });// and get the resultsString result = serializer.Serialize(MyObjectInstance);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/418394.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号