zoukankan      html  css  js  c++  java
  • Json数据序列化对象,及对象序列化为Json格式

    View Code
    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获取Dictionary集合
    /// </summary>
    /// <param name="szJson"></param>
    /// <returns></returns>
    public static Dictionary<string, string> GetDictionaryFromJson(string szJson)
    {
    Dictionary<string, string> list = new Dictionary<string, string>();

    System.Web.Script.Serialization.JavaScriptSerializer jsonConvert = new System.Web.Script.Serialization.JavaScriptSerializer();
    list = jsonConvert.Deserialize<Dictionary<string, string>>(szJson);

    return list;
    }
    }
  • 相关阅读:
    STM32驱动TEA5767收音机模块
    stm32驱动DS1302芯片
    NRF24L01无线通讯模块驱动
    MQ-2烟雾传感器启动
    HCSR04超声波传感器驱动
    RDA5820收音机芯片驱动
    SD卡初始化以及命令详解
    STM32硬件IIC操作
    STM32驱动MPU6050
    BMP085气压传感器驱动
  • 原文地址:https://www.cnblogs.com/snlfq2000/p/2337209.html
Copyright © 2011-2022 走看看