我从 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/