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; }



  • 相关阅读:
    这是另外一篇
    使用客户端写博客
    vim编码相关配置
    给eclipse装一些插件
    手机型号收集
    解决黑苹果与windows时区不一致
    记录一些在VPS上折腾的东西
    一个获取文件绝对路径的sh
    python批量GBK转UTF-8
    用NDK编译lua库
  • 原文地址:https://www.cnblogs.com/Benjamin/p/3612083.html
Copyright © 2011-2022 走看看