zoukankan      html  css  js  c++  java
  • C#使用JSON相关

    一、Json字符串转换为Dictionary

            /// <summary>
            /// JSON字符串转为  Dictionary
           /// </summary>
           /// <typeparam name="TKey"></typeparam>
           /// <typeparam name="TValue"></typeparam>
           /// <param name="jsonStr"></param>
           /// <returns></returns>
            public static Dictionary<string, string> DeserializeStringToDictionary<TKey, TValue>(string jsonStr)
            {
                if (string.IsNullOrEmpty(jsonStr))
                    return new Dictionary<string, string>();
    
                Dictionary<string, string> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonStr);
                                
                return jsonDict;
    
            }

    二、解析json

    JObject解析单个Json;

    JArray(解析匿名Json数组);

    JsonConvert.DeserializeObject(反序列化json)

          ①添加using Newtonsoft.Json.Linq引用

          ②相关方法

    •         遍历json对象(解析单个json)      
                   var josn = new { ID = "11", Name = "Test", Sex = "" };
                    string strJson = JsonConvert.SerializeObject(josn);
                    JObject jsonObj = JObject.Parse(strJson);
                    string strID=jsonObj["ID"].ToString().Trim();
    • 数组类型的json对象
                  var v1 = new { ID = "11", Name = "T1", Sex = "" };
                    var v2 = new { ID = "22", Name = "T2", Sex = "" };
                    var josn = new { v1, v2 };
                    string strJosn = JsonConvert.SerializeObject(josn);
                    JArray ja = JArray.Parse(strJosn);
                    for (int i = 0; i < ja.Count; i++)
                    {
                        JObject jsonOB = JObject.Parse(ja[i].ToString().Trim());
                        string strID = jsonOB["ID"].ToString().Trim();
                    }
  • 相关阅读:
    DeviceIOControl读写硬盘设备
    #ifdef的用法
    更改Visual Studio 2010的主题设置[.vssettings格式]
    vc2010 vs2010 智能插件Visual Assist 安装,设置
    VS2010 C++ 操作Excel表格的编程实现
    Python 字符串
    配置opencv2.4.11生成release版本
    配置opencv2.411调试版本(debug)
    边沿检测与提取,轮廓跟踪
    CComboBox控件的使用 1
  • 原文地址:https://www.cnblogs.com/mengzhixingping/p/14153925.html
Copyright © 2011-2022 走看看