C#将字符串转换为字典

130*_*13a 3 c# string dictionary system.net

我从Bitly api 得到这个响应字符串:

{ "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
    }
}
Run Code Online (Sandbox Code Playgroud)

如何将此字符串转换为字典,如何访问键的值"url"(不包括所有字符串\)

Avn*_*tan 7

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

而不是重新发明轮子和解析JSON自己,我建议你使用现有的JSON库为C#,如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
Run Code Online (Sandbox Code Playgroud)


Joh*_*ger 5

如果将 Newtonsoft 的 Json 之类的包添加到项目中,则可以将 Json 反序列化为匿名类型。然后您可以从中获取网址。这可通过 Visual Studio 中的 NuGet 获得,并提供对异步或同步序列化/反序列化的支持。

public string GetUrl(string bitlyResponse)
{
    var responseObject = new
    {
        data = new { url = string.Empty },
    };

    responseObject = JsonConvert.DeserializeAnonymousType(bitlyResponse, responseObject);
    return responseObject.data.url;
}
Run Code Online (Sandbox Code Playgroud)