Json 및 패키지된 Json 분석

3288 단어 C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Monitor
{
    /// 
    /// FileName: JSONHelper.cs
    /// CLRVersion: 2.0.50727.3623
    /// Author: Mikel
    /// Corporation:
    /// Description:JSON         
    /// 1. List        JSON  
    /// 2. T       JSON    
    /// 3. JSON       T    
    /// DateTime: 2011-09-13 14:11:34
    /// 
    public static class JsonHelper
    {
        /// 
        ///      JSON    
        /// 
        ///  
        ///   
        ///      JSON  
        public static string GetJSON(object obj)
        {
            string result = String.Empty;
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
                using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    serializer.WriteObject(ms, obj);
                    result = System.Text.Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }
        /// 
        ///   List    JSON  
        /// 
        ///  
        ///    
        /// JSON    
        public static string JSON(List vals)
        {
            System.Text.StringBuilder st = new System.Text.StringBuilder();
            try
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
 
                foreach (T city in vals)
                {
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                    {
                        s.WriteObject(ms, city);
                        st.Append(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
 
            return st.ToString();
        }
        /// 
        /// JSON       T     
        /// 
        /// 
        /// 
        /// 
        public static T ParseFormByJson(string jsonStr)
        {
            T obj = Activator.CreateInstance();
            using (System.IO.MemoryStream ms =
            new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr)))
            {
                System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(ms);
            }
        }
    }
}

페이지 호출
C# code
?
2 Online foo = JsonHelper.ParseFormByJson(json);
//온라인에서 직접 작성한 엔티티 클래스

좋은 웹페이지 즐겨찾기