首页 新闻 会员 周边 捐助

反序列化实体

0
悬赏园豆:5 [已关闭问题]

这里是一个实体类

[DataContract(Name="UserInfo")]
public class User
{
[DataMember(Name
= "ID")]
public string UserID{get;set;}

[DataMember(Name
="Name")]
public string UserName { get; set; }

[DataMember(Name
="Pwd")]
public string UserPwd { get; set; }

[DataMember(Name
="Sex")]
public bool Sex { get; set; }

[DataMember(Name
="Age")]
public int Age { get; set; }
}

通过AJAX发送回数据
{
"CalssName":"UserInfo",
"ClassData":"{"ID":"530332","Name":"张三","Pwd":"123456","Sex":"0","Age":"20"}"
}
怎么样把它"反序列化"
来生成一个User实体对象
问题补充: 这个和反射有什么关系吗? 我的名称空间是GradView.Lib.Data(实体) 前台发回来的Ajax数据可以改变结构.
Giant150的主页 Giant150 | 小虾三级 | 园豆:1172
提问于:2009-08-28 12:21
< >
分享
其他回答(4)
0

这篇文章可以帮你解答这个问题。

http://www.cnblogs.com/trance/archive/2009/08/03/1537648.html

风影极光 | 园豆:1573 (小虾三级) | 2009-08-28 13:15
0

不会AJAX,帮你顶,留个印。

winzheng | 园豆:8797 (大侠五级) | 2009-08-28 13:31
0

你可以在MSDN中搜索关于JavaScriptSerializer的信息

也可以参考这篇文章 http://www.cnblogs.com/myssh/archive/2009/07/07/1518758.html

Yuxin Yang | 园豆:215 (菜鸟二级) | 2009-08-28 14:16
0

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Reflection;

namespace TestCmdApp
{
    class UserInfo
    {
        public string Name { get; set; }

        public int Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string json = "{ ClassName: 'UserInfo', ClassData: { Name: 'Gray', Age: 24 } }";
            UserInfo user = DeserializeJsonObject<UserInfo>(json);

            Console.Read();
        }

        public static T DeserializeJsonObject<T>(string json) where T : new()
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string, object> dic = serializer.DeserializeObject(json) as Dictionary<string, object>;

            string className = dic["ClassName"] as string;
            Dictionary<string, object> classData = dic["ClassData"] as Dictionary<string, object>;

            Type type = typeof(T);
            object instance = Activator.CreateInstance(type);
            foreach (PropertyInfo property in type.GetProperties())
            {
                if (property.CanWrite)
                {
                    object value = classData[property.Name];
                    if (value != null)
                    {
                        property.SetValue(instance, value, null);
                    }
                }
            }

            return (T)Convert.ChangeType(instance, typeof(T));
        }
    }
}

Gray Zhang | 园豆:17610 (专家六级) | 2009-08-28 15:34
0

使用 LinqToJOSN

麦舒 | 园豆:452 (菜鸟二级) | 2009-08-28 20:33
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册