好记性不如烂笔头。

JSON参数校验

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;

namespace System
{
    public static class JsonValidExtension
    {
        /// 
        /// JSON参数校验
        /// 
        ///
        ///dic.Add("pwd","密码")
        /// 
        public static string ValidJSONNotNullOrEmpty(this string jsonStr, Dictionary<string, string> field)
        {
            return ValidJSONNotNullOrEmpty2(jsonStr, field);
        }
        /// 
        /// JSON参数校验
        /// 
        ///
        ///dic.Add("pwd","密码")
        ///JArray 对象
        /// 
        public static string ValidJSONNotNullOrEmpty(this string jsonStr, Dictionary<string, string> field, out JArray jarr)
        {
            return ValidJSONNotNullOrEmpty2(jsonStr, field, out jarr);
        }

        /// 
        /// JSON参数校验
        /// 
        ///
        ///dic.Add("pwd","密码")
        ///JObject 对象
        /// 
        public static string ValidJSONNotNullOrEmpty(this string jsonStr, Dictionary<string, string> field, out JObject jobj)
        {
            return ValidJSONNotNullOrEmpty2(jsonStr, field, out jobj);
        }

        /// 
        /// JSON参数校验
        /// 
        ///
        ///"name,pwd"
        /// 
        public static string ValidJSONNotNullOrEmpty(this string jsonStr, string fields)
        {
            if (string.IsNullOrEmpty(fields)) throw new ArgumentNullException("fields");
            fields = fields.Replace(',', ',');
            return ValidJSONNotNullOrEmpty2(jsonStr, ToDictionary(fields.Split(',')));
        }
        /// 
        /// JSON参数校验
        /// 
        ///
        ///"name,pwd"
        ///JArray对象
        /// 
        public static string ValidJSONNotNullOrEmpty(this string jsonStr, string fields, out JArray jarr)
        {
            if (string.IsNullOrEmpty(fields)) throw new ArgumentNullException("fields");
            fields = fields.Replace(',', ',');
            return ValidJSONNotNullOrEmpty2(jsonStr, ToDictionary(fields.Split(',')), out jarr);
        }
        /// 
        /// JSON参数校验
        /// 
        ///
        ///"name,pwd"
        ///JObject对象
        /// 
        public static string ValidJSONNotNullOrEmpty(this string jsonStr, string fields, out JObject jobj)
        {
            if (string.IsNullOrEmpty(fields)) throw new ArgumentNullException("fields");
            fields = fields.Replace(',', ',');
            return ValidJSONNotNullOrEmpty2(jsonStr, ToDictionary(fields.Split(',')), out jobj);
        }

        /// 
        /// JSON参数校验
        /// 
        ///
        ///new string[]{"name","pwd"}
        /// 
        public static string ValidJSONNotNullOrEmpty(this string jsonStr, string[] fields)
        {
            if (fields.Length == 0) throw new ArgumentNullException("fields");
            return ValidJSONNotNullOrEmpty2(jsonStr, ToDictionary(fields));
        }
        /// 
        /// JSON参数校验
        /// 
        ///
        ///new string[]{"name","pwd"}
        ///JArray对象
        /// 
        public static string ValidJSONNotNullOrEmpty(this string jsonStr, string[] fields, out JArray jarr)
        {
            if (fields.Length == 0) throw new ArgumentNullException("fields");
            return ValidJSONNotNullOrEmpty2(jsonStr, ToDictionary(fields), out jarr);
        }
        /// 
        /// JSON参数校验
        /// 
        ///
        ///new string[]{"name","pwd"}
        ///JObject对象
        /// 
        public static string ValidJSONNotNullOrEmpty(this string jsonStr, string[] fields, out JObject jobj)
        {
            if (fields.Length == 0) throw new ArgumentNullException("fields");
            return ValidJSONNotNullOrEmpty2(jsonStr, ToDictionary(fields), out jobj);
        }
        /// 
        /// 验证json序列化后的实体对象,不为空的属性需要加NotNull特性
        /// 
        /// 验证对象的类型
        ///
        ///验证对象的类型
        /// 
        public static string ValidJSONNotNullOrEmpty(this string jsonStr, T targetType)
        {
            StringBuilder strb = new StringBuilder();
            if (null == targetType) strb.Append("校验对象为null ");
            else
            {
                Type type = targetType.GetType();
                PropertyInfo[] pis = type.GetProperties();
                foreach (PropertyInfo item in pis)
                {
                    if (null != (item.GetCustomAttribute(typeof(NotNullAttribute)) as NotNullAttribute))
                    {
                        object v = item.GetValue(targetType);
                        if (null == v || string.IsNullOrEmpty(v.ToString())) strb.AppendFormat("{0}, ", item.Name);
                    }
                }
            }
            if (!string.IsNullOrEmpty(strb.ToString()))
            {
                strb.Append("不能为空");
                NLog.LogManager.GetCurrentClassLogger().Warn(strb.ToString());
            }
            return strb.ToString();
        }

        static string ValidJSONNotNullOrEmpty2(string jsonStr, Dictionary<string, string> field)
        {
            try
            {
                switch (JToken.Parse(jsonStr).Type)
                {
                    case JTokenType.Array:
                        JArray jarr = JArray.Parse(jsonStr);
                        return ValidJArray(jarr, field);
                    case JTokenType.Object:
                        JObject jobj = JObject.Parse(jsonStr);
                        return ValidJObject(jobj, field);
                }
            }
            catch
            {
                return "JSON格式错误";
            }
            return null;
        }
        static string ValidJSONNotNullOrEmpty2(string jsonStr, Dictionary<string, string> field, out JArray jarr)
        {
            jarr = null;
            try
            {
                switch (JToken.Parse(jsonStr).Type)
                {
                    case JTokenType.Array:
                        jarr = JArray.Parse(jsonStr);
                        return ValidJArray(jarr, field);
                    case JTokenType.Object:
                        JObject jobj = JObject.Parse(jsonStr);
                        return ValidJObject(jobj, field);
                }
            }
            catch
            {
                return "JSON格式错误";
            }
            return null;
        }
        static string ValidJSONNotNullOrEmpty2(string jsonStr, Dictionary<string, string> field, out JObject jobj)
        {
            jobj = null;
            try
            {
                switch (JToken.Parse(jsonStr).Type)
                {
                    case JTokenType.Array:
                        JArray jarr = JArray.Parse(jsonStr);
                        return ValidJArray(jarr, field);
                    case JTokenType.Object:
                        jobj = JObject.Parse(jsonStr);
                        return ValidJObject(jobj, field);
                }
            }
            catch
            {
                return "JSON格式错误";
            }
            return null;
        }
        static string ValidJObject(JObject jobj, Dictionary<string, string> field)
        {
            string validResult = null;
            foreach (var item in jobj)
            {
                validResult = Valid(item, field);
                if (!string.IsNullOrEmpty(validResult)) return validResult;
            }
            return null;
        }
        static string Valid(KeyValuePair<string, JToken> kvp, Dictionary<string, string> field)
        {
            //验证参数名不区分大小写
            Dictionary<string, string> temp = new Dictionary<string,string>();
            foreach (var item in field) temp.Add(item.Key.ToLower(), item.Value);

            string validResult = null;
            switch (kvp.Value.Type)
            {
                case JTokenType.Array:
                    validResult = ValidJArray((JArray)kvp.Value, temp);
                    if (!string.IsNullOrEmpty(validResult)) return validResult;
                    break;
                case JTokenType.Object:
                    validResult = ValidJObject((JObject)kvp.Value, temp);
                    if (!string.IsNullOrEmpty(validResult)) return validResult;
                    break;
                default:
                    if (string.IsNullOrEmpty(kvp.Value.ToString()))
                        if (temp.ContainsKey(kvp.Key.ToLower())) return temp[kvp.Key.ToLower()] + "不能为空";
                    break;
            }
            return null;
        }
        static string ValidJArray(JArray jarr, Dictionary<string, string> field)
        {
            string validResult = null;
            foreach (var item in jarr)
            {
                switch (item.Type)
                {
                    case JTokenType.Array:
                        validResult = ValidJArray((JArray)item, field);
                        if (!string.IsNullOrEmpty(validResult)) return validResult;
                        break;
                    case JTokenType.Object:
                        validResult = ValidJObject((JObject)item, field);
                        if (!string.IsNullOrEmpty(validResult)) return validResult;
                        break;
                }
            }
            return null;
        }
        static Dictionary<string, string> ToDictionary(string[] fields)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (var item in fields) dic.Add(item, "参数");
            return dic;
        }
    }
}