C# 将字符串转换为字典

标签 c# string dictionary system.net

我从 Bitly 得到这个响应字符串应用程序接口(interface):

{ "status_code": 200,
  "status_txt": "OK",
  "data":
    { "long_url": "http:\/\/amazon.de\/",
      "url": "http:\/\/amzn.to\/1mP2o58",
      "hash": "1mP2o58",
      "global_hash": "OjQAE",
      "new_hash": 0
    }
}

如何将此字符串转换为字典以及如何访问键 "url" 的值(没有所有 \)

最佳答案

这不仅仅是一些普通的字符串。这是JSON中的一个数据结构格式,一种常见且完善的格式,最初用于 Javascript,但现在作为服务和客户端之间的数据传输机制相当普遍。

与其重新发明轮子并自己解析 JSON,我建议您使用现有的 C# JSON 库,例如 JSON.NET ,它将吃掉该字符串并为您将其解析为 .NET 对象。

这是一个代码示例,取自 JSON.NET 的文档,显示了它的用法:

string json = @"{
'href': '/account/login.aspx',
'target': '_blank'
 }";

Dictionary<string, string> htmlAttributes =                 
 JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

Console.WriteLine(htmlAttributes["href"]);
   // /account/login.aspx

Console.WriteLine(htmlAttributes["target"]);
   // _blank

关于C# 将字符串转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24710535/

相关文章:

c# - 如何生成唯一的 8 位数字?

string - find_if 在字符串数组上

C# 从文件名中删除无效字符

python - 比较jinja flask 模板中字典的长度

c# - 如何在我的 XML 中找到所有子节点

c# - WPF - 将数据从 DAL 传递到 UI

node.js - 使用地理位置确定哪些用户与某个用户接近

python - 为什么 "{1: ' a', True : 'b' , 1.0 : 'c' , 1.00 : 'd' }"evaluate to "{1: 'd' }"?

c# - 通用Http模块

c++ - 在 C++ 中进行字符串连接后崩溃