解析Json和封装Json

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); //Online 自己写的实体类

你可能感兴趣的:(C#)