zoukankan      html  css  js  c++  java
  • .net JsonHelper json帮助类

    using Newtonsoft.Json;
    using System.Runtime.Serialization.Json;
    using System.Text;
    
        public class JsonHelper
        {
            /// <summary>  
            /// 生成Json格式  
            /// </summary>  
            /// <typeparam name="T"></typeparam>  
            /// <param name="obj"></param>  
            /// <returns></returns>  
            public static string GetJson<T>(T obj)
            {
                DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
                using (MemoryStream stream = new MemoryStream())
                {
                    json.WriteObject(stream, obj);
                    string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson;
                }
            }
            /// <summary>  
            /// 获取Json的Model  
            /// </summary>  
            /// <typeparam name="T"></typeparam>  
            /// <param name="szJson"></param>  
            /// <returns></returns>  
            public static T ParseFromJson<T>(string szJson)
            {
                T obj = Activator.CreateInstance<T>();
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                    return (T)serializer.ReadObject(ms);
                }
            }
    
            /// <summary>
            /// 解析JSON数组生成对象实体集合
            /// </summary>
            /// <typeparam name="T">对象类型</typeparam>
            /// <param name="json">json数组字符串(eg.[{"ID":"1","Name":"lttr"}])</param>
            /// <returns>对象实体集合</returns>
            public static List<T> DeserializeJsonToList<T>(string json) where T : class
            {
                JsonSerializer serializer = new JsonSerializer();
                StringReader sr = new StringReader(json);
                object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
                List<T> list = o as List<T>;
                return list;
            }
        }
  • 相关阅读:
    证明 O(n/1+n/2+…+n/n)=O(nlogn)
    ZOJ 3623 Battle Ships DP
    ZOJ 3631 Watashi's BG DFS
    ZOJ 3622 Magic Number 打表找规律
    poj 1088 滑雪 记忆化搜索
    poj 1273 Drainage Ditches 网络流最大流基础
    Codeforces Round #243 (Div. 1)A. Sereja and Swaps 暴力
    UVALive 5059 C
    Codeforces Round #295 (Div. 2)C
    Codeforces Round #295 (Div. 2)B
  • 原文地址:https://www.cnblogs.com/GoCircle/p/9708156.html
Copyright © 2011-2022 走看看