首页 > 解决方案 > 从 httpclient 的响应字符串中的键中获取值

问题描述

我正在尝试使用System.Net.Http. 键以字典的字符串表示形式返回。

我的响应字符串看起来像这样,一个字典的字符串表示形式:

"{\"primaryKey\": \"hereIsMyKeyValue\",\"secondaryKey\":\"jsfidjsi\"}"

相关代码

这就是我现在正在做的发布请求并阅读我的回复

var response = await httpClient.PostAsync(url, content);

var responseString = await response.Content.ReadAsStringAsync();

我试过的

我尝试使用.Trim()摆脱转义字符\。但这无济于事。

   var test = responseString.Trim();

如何获取字符串表示中的任何一个键的内容?还是我通过尝试操纵从返回的内容来解决问题response.Content.ReadAsStringAsync()

标签: c#httpclientdotnet-httpclient

解决方案


对你正在尝试的事情做一些假设,

您可能想使用像 NewtonSoft 这样的东西来反序列化 Json:

class MyDictionaryItem
{
    [JsonProperty("primaryKey")]
    public string PrimaryKey { get; set; }

    [JsonProperty("secondaryKey")]
    public string SecondaryKey { get; set; }
}

var myResult = JsonConvert.DeserializeObject<MyDictionaryItem>(responseString);

然后,您可以作为 的成员访问您想要的值myResult


推荐阅读