• json 的相互 转换


    using System.Runtime.Serialization.Json;

    //json 转化为List集合

    public List<T> JSONStringToList<T>(string strJson)
    {
    JavaScriptSerializer serializer = new JavaScriptSerializer();

    //List<T> objList = serializer.Deserialize<List<T>>(strJson);
    List<T> objList = Deserialize<List<T>>(strJson);
    return objList;
    }

    public static T Deserialize<T>(string json)
    {

    T obj = Activator.CreateInstance<T>();

    using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
    {

    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());

    return (T)serializer.ReadObject(ms);
    }

    }

    //===================================

    /// <summary>
    /// DataTable转JsonString
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static string DataTableToJsonString(DataTable dt)
    {
    StringBuilder sb = new StringBuilder();
    if (dt != null && dt.Rows.Count > 0)
    {

    foreach (DataRow dr in dt.Rows)
    {
    string row = string.Empty;
    for (int i = 0; i < dt.Columns.Count; i++)
    {
    row += string.Format(","{0}":"{1}"", dt.Columns[i].ColumnName, dr[i]);
    }
    if (row.Length>0)
    {
    row = row.Remove(0, 1);

    }
    sb.AppendFormat(",{{{0}}}",row);
    }
    sb.Remove(0, 1);
    sb.Insert(0,"[");
    sb.Append("]");

    }
    return sb.ToString();
    }

  • 相关阅读:
    异常单据锁定涉及的数据库表
    用友通只启用核算模块
    一个迟到MM如何让老师疯掉的
    偷偷看,别笑出声啊
    安装时又提示删除程序
    自动折行的设置
    酒后百态新编 恶搞
    系统管理中“站点”“运行状态”的含义
    神经病女士银行取钱
    HDOJ 1017
  • 原文地址:https://www.cnblogs.com/yangjinwang/p/4325731.html
Copyright © 2020-2023  润新知