简体   繁体   中英

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 . 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 \\ . 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() ?

Making a few assumptions about what you are attempting,

You probably want to use something like NewtonSoft to deserialize the 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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