c# - 从 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()
?
解决方案
对你正在尝试的事情做一些假设,
您可能想使用像 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
。
推荐阅读
- vim - 在 GNU Screen 中运行 Vim:如何避免 Shift+left/right 删除字符
- oracle - 为 FK 导入 Oracle 转储文件和 NOVALIDATE
- docker - 如何在我的 gitlab 工作中与我的服务进行通信?
- javascript - 画布 toDataURL 返回空
- python - 在 ubuntu 中使用参数运行 .py 文件主函数
- react-native - React Native LinearGradient 重叠导航器
- reactjs - 如何在反应中创建重定向特定路由?
- python - Python:如何在列表中找到相同的值并将它们分组到一个新列表中?
- javascript - Javascript - 从本地主机上发出的请求中获取外部 IP 地址
- python - 如果它不为null,如何将变量添加到render_template?