一个简单的Json帮助类

Posted 淺笑嫣然

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一个简单的Json帮助类相关的知识,希望对你有一定的参考价值。

贴上一个简单的Json帮助类,代码如下:

public class JsonHelper
    {
        /// <summary>
        /// 实体类转Json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public  T JsonStringToClass<T>(string jsonString)
        {
            using (var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonString)))
            { return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms); }
        }
        /// <summary>
        /// Json转实体类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonObject"></param>
        /// <returns></returns>
        public  string ClassToJsonString<T>(T jsonObject)
        {
            using (var ms = new MemoryStream())
            {
                new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject);
                return System.Text.Encoding.UTF8.GetString(ms.ToArray());
            }
        }
        /// <summary>
        /// Json格式化
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public string JsonFormate(string json)
        {
            int Level = 0;
            var JsonArr = json.ToArray();
            string JsonTree = string.Empty;
            for(int i = 0; i < json.Length; i++)
            {
                char c = JsonArr[i];
                if (Level > 0 && ‘\n‘ == JsonTree.ToArray()[JsonTree.Length - 1])
                {
                    JsonTree += TreeLevel(Level);
                }
                switch (c)
                {
                    //case ‘{‘:
                    //    JsonTree +="\r\n"+c ;
                    //    break;
                    //case ‘}‘:
                    //    JsonTree += "\r\n"+c;
                        //break;
                    case ‘[‘:
                        JsonTree += c + "\r\n";
                        Level++;
                        break;
                    case ‘,‘:
                        JsonTree += c + "\r\n";
                        break;
                    case ‘]‘:
                        JsonTree += "\r\n";
                        Level--;
                        JsonTree += TreeLevel(Level);
                        JsonTree+=c;
                        break;
                    default:
                        JsonTree += c;
                        break;
                }
            }
            return JsonTree;
        }
        string TreeLevel(int level)
        {
            string leaf = string.Empty;
            for (int t = 0; t < level; t++)
            {
                leaf += "\t";
            }
            return leaf;
        }
        /// <summary>
        /// Json文件格式化
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public string JsonFileFormatte(string filepath)
        {
            try
            {
                if (!File.Exists(filepath))
                {
                    return "传入文件不存在!";
                }
                string str = File.ReadAllText(filepath);
                 str = JsonFormate(str);
                File.WriteAllText(filepath, str);
                return "操作已成功!";
            }catch(Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// Json转成实体类
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public dynamic ConvertJsonToDynamic(string json)
        {
            javascriptSerializer jss = new JavaScriptSerializer();
            jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });
            dynamic dy = jss.Deserialize(json, typeof(object)) as dynamic;
            return dy;

        }
    }

    class DynamicJsonConverter : JavaScriptConverter
    {
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");

            if (type == typeof(object))
            {
                return new DynamicJsonObject(dictionary);
            }

            return null;
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            throw new NotImplementedException();
        }
        public override IEnumerable<Type> SupportedTypes
        {
            get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); }
        }
    }
    class DynamicJsonObject : DynamicObject
    {
        private IDictionary<string, object> Dictionary { get; set; }

        public DynamicJsonObject(IDictionary<string, object> dictionary)
        {
            this.Dictionary = dictionary;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = this.Dictionary[binder.Name];

            if (result is IDictionary<string, object>)
            {
                result = new DynamicJsonObject(result as IDictionary<string, object>);
            }
            else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
            {
                result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
            }
            else if (result is ArrayList)
            {
                result = new List<object>((result as ArrayList).ToArray());
            }

            return this.Dictionary.ContainsKey(binder.Name);
        }
    }

以上是关于一个简单的Json帮助类的主要内容,如果未能解决你的问题,请参考以下文章

具有 Java 绑定能力的简单模板库

简单的 jQuery SlickGrid JSON 示例或文档

apache_conf 一个简单的配置类,用于加载和保存到本地config.json文件。

如何将我的类对象转换为 JSON for Alamofire

如何编写一个grafana简单的json到python中的json表查询

用 JsonPath 帮助处理复杂 JSON