从来自 httpclient 的响应字符串中的键中获取值
Grabbing value from a key from a response string from httpclient
我正在尝试使用 System.Net.Http
从 post 请求中获取一个值。键以字典的字符串表示形式返回。
我的响应字符串看起来像这样,字典的字符串表示形式:
"{\"primaryKey\": \"hereIsMyKeyValue\",\"secondaryKey\":\"jsfidjsi\"}"
相关代码
这就是我现在正在做的,以发出 post 请求并阅读我的回复
var response = await httpClient.PostAsync(url, content);
var responseString = await response.Content.ReadAsStringAsync();
我试过的
我尝试使用 .Trim()
去除转义字符 \
。但这没有任何作用。
var test = responseString.Trim();
如何获取字符串表示形式中的任一键的内容?还是我通过尝试操纵从 response.Content.ReadAsStringAsync()
返回的内容来解决问题?
对您的尝试做出一些假设,
您可能想使用 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
的成员访问您想要的值。
我正在尝试使用 System.Net.Http
从 post 请求中获取一个值。键以字典的字符串表示形式返回。
我的响应字符串看起来像这样,字典的字符串表示形式:
"{\"primaryKey\": \"hereIsMyKeyValue\",\"secondaryKey\":\"jsfidjsi\"}"
相关代码
这就是我现在正在做的,以发出 post 请求并阅读我的回复
var response = await httpClient.PostAsync(url, content);
var responseString = await response.Content.ReadAsStringAsync();
我试过的
我尝试使用 .Trim()
去除转义字符 \
。但这没有任何作用。
var test = responseString.Trim();
如何获取字符串表示形式中的任一键的内容?还是我通过尝试操纵从 response.Content.ReadAsStringAsync()
返回的内容来解决问题?
对您的尝试做出一些假设,
您可能想使用 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
的成员访问您想要的值。