简体   繁体   English

从httpclient的响应字符串中获取键的值

[英]Grabbing value from a key from a response string from httpclient

I am trying to grab a value from a post request using System.Net.Http . 我试图使用System.Net.Http从发布请求中获取值。 The keys are returned in a string representation of a dictionary. 键以字典的字符串表示形式返回。

My response string looks something like this, a string representation of a dictionary: 我的响应字符串看起来像这样,字典的字符串表示形式:

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

Relevant code 相关代码

This is what I am doing right now to make the post request and reading my response 这是我现在正在做的工作,以发出职位请求并阅读我的回复

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

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

What I've tried 我尝试过的

I tried using .Trim() to get rid of the escape characters \\ . 我尝试使用.Trim()摆脱转义字符\\ but that does nothing. 但这无能为力。

   var test = responseString.Trim();

How can I grab the contents of either of those keys that's in the string representation? 如何获取字符串表示形式中的那些键的内容? Or am I approaching the problem by trying to manipulate what is returned from response.Content.ReadAsStringAsync() ? 还是我通过尝试处理response.Content.ReadAsStringAsync()返回的内容来解决问题?

Making a few assumptions about what you are attempting, 对您的尝试做一些假设,

You probably want to use something like NewtonSoft to deserialize the Json: 您可能想使用类似NewtonSoft的方法反序列化Json:

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

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

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

You can then access the value you want as a member of myResult . 然后,您可以作为myResult成员访问所需的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM