zoukankan      html  css  js  c++  java
  • 服务器端接受Json数据的绑定实现

    1、在方法参数前加上JsonRead<T>的泛型特性

     public ActionResult GetData([JsonRead(typeof(PostData))]PostData postData)

    2、继承CustomModelBinder类:

    public class JsonReadAttribute : CustomModelBinderAttribute
        {
            private Type type;
            public JsonReadAttribute(Type type)
            {
                this.type = type;
            }
            public override IModelBinder GetBinder()
            {
                return new JsonReadModelBinder(type);
            }
        }

    3、其中JsonReadModelBinder实现IModelBinder接口

    public class JsonReadModelBinder : IModelBinder
        {
            private Type type;
            public JsonReadModelBinder(Type type)
            {
                this.type = type;
            }
    
            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                var request = controllerContext.HttpContext.Request;
                request.InputStream.Position = 0;
                var objs = new object();
                using (var s = new GZipStream(request.InputStream, CompressionMode.Decompress))
                {
                    using (var sReader = new StreamReader(s, Encoding.UTF8))
                    {
                        string str = sReader.ReadToEnd();
                        if (type == typeof(PostData))
                        {
                            objs = JsonUnit.Deserialize<PostData>(str);
                        }else if (type == typeof(PostComment))
                        {
                            objs = JsonUnit.Deserialize<PostComment>(str);
                        }//if else 扩展
                        sReader.Close();
    } }
    return objs; }



  • 相关阅读:
    matlab cell
    matlab linux 快捷键设置——有问题还是要解决
    latex 小结
    TOJ 1258 Very Simple Counting
    TOJ 2888 Pearls
    HDU 1248 寒冰王座
    TOJ 3486 Divisibility
    TOJ 3635 过山车
    TOJ 1840 Jack Straws
    HDU 4460 Friend Chains
  • 原文地址:https://www.cnblogs.com/Benjamin/p/3612083.html
Copyright © 2011-2022 走看看