Convert JSON object to Custom C# object

最近开发的项目中遇到一个问题,需要批量添加用户,用户信息在View里是一个Javascript对象,多个用户组成一个数组,然后提交到Control。
Google查询了些资料,把问题解决了,在这记录下。

    var userList=[];
    var userA={
        Name:"张三",
        UserId: "zhangsan",
        GroupId: 1121
    }
    var userB={
        Name:"李四",
        UserId: "lisi",
        GroupId: 4542
    }
    userList.push(userA);
    userList.push(userB);

第一部是将数组序列化:

//对象序列化(支持数组与对象)
var serialize = function (_obj) {
    // Let Gecko browsers do this the easy way
    if (typeof _obj.toSource !== 'undefined' && typeof _obj.callee === 'undefined') {
        return _obj.toSource();
    }
    // Other browsers must do it the hard way
    switch (typeof _obj) {
        // numbers, booleans, and functions are trivial:   
        // just return the object itself since its default .toString()   
        // gives us exactly what we want   
        case 'number':
        case 'boolean':
        case 'function':
            return _obj;
            break;

        // for JSON format, strings need to be wrapped in quotes   
        case 'string':
            return ''' + _obj + ''';
            break;

        case 'object':
            var str;
            if (_obj.constructor === Array || typeof _obj.callee !== 'undefined') {
                str = '[';
                var i, len = _obj.length;
                for (i = 0; i < len - 1; i++) { str += serialize(_obj[i]) + ','; }
                str += serialize(_obj[i]) + ']';
            }
            else {
                str = '{';
                var key;
                for (key in _obj) { str += key + ':' + serialize(_obj[key]) + ','; }
                str = str.replace(/,$/, '') + '}';
            }
            return str;
            break;

        default:
            return 'UNKNOWN';
            break;
    }
}

//序列化数组
var serializeStr = serialize(userList);
//Ajax提交
$.ajax({
    type:"POST",
    url:"/Admin/AddGroupUsers",
    data:{users: serializeStr},
    success:function(){}
});

再来看后台处理Json的方法,把Json字符串转换成List<>&Object

    //引用
    using System.Web.Mvc;
    using System.Web.Script.Serialization;

    public class JsonBinder<T> : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            //从请求的参数中提取参数数据
            var json = controllerContext.HttpContext.Request.Form[bindingContext.ModelName] as string;

            // 提的参数是对象
            if (json.StartsWith("{") && json.EndsWith("}"))
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                object obj = js.Deserialize<T>(json);
                return obj;
            }

            // 提的参数是对象数组
            if (json.StartsWith("[") && json.EndsWith("]"))
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                List<T> obj = js.Deserialize<List<T>>(json);

                return obj;
            }


            return null;
        }
    }

        //Control中调用JsonBinder
        public ActionResult AddGroupUsers([ModelBinder(typeof(JsonBinder<UserEditInfo>))]List<UserEditInfo> users, int groupKeyId) 
        {
            var hasFail = false;
            var failNames=string.Empty;
            foreach (var item in users)
            {
                var retVal = AddGroupMultiUser(item);
                if (retVal.IsError)
                {
                    hasFail = true;
                    failNames += item.Name + "(" + item .UserId+ ") ";
                }
            }
            if (hasFail)
            {
                TempData["State"] = "添加失败!";
                TempData["ErrorMsg"] = failNames;
            }
            else {
                TempData["State"] = "添加成功!";
            }

            var userService = new User(unitOfWork);
            return RedirectToAction("GroupUser", "Admin", new
            {
                id = groupKeyId
            });
        }

发表评论

电子邮件地址不会被公开。 必填项已用*标注