0

I have the following code:

var response = await client.PostAsync("http://localhost/test-request", content);

var responseString = await response.Content.ReadAsStringAsync();
var responseJSON = JsonConvert.DeserializeObject(responseString);

Console.WriteLine("Finished");

MessageBox.Show("Hi", responseJSON.value, MessageBoxButtons.OK);

The responseString comes back properly but i'm trying to convert it to an object so I can do more advanced stuff with the return value.

The problem is, C# / Visual Studio is complaining that responseJSON.value does not have a value (which it doesn't until the Async operation is complete)

How do I get around this problem?

4
  • 1
    You are attempting to deserialize to object, that's likely the problem. The asynchronous part of the function is done much earlier than that Commented May 23, 2018 at 23:30
  • You might want JObject.Parse(responseJson) or you might want to create a class that represents the json schema and deserialize to that specific type. Commented May 23, 2018 at 23:34
  • you can deseiralize to dynamic if you do not have a concrete class available Commented May 23, 2018 at 23:35
  • Could you return an instance directly using ReadAsAsync? E.g. var response = await response.Content.ReadAsAsync<MyClass>(); Commented May 23, 2018 at 23:42

1 Answer 1

1
var responseJSON = JsonConvert.DeserializeObject(responseString);

creates responseJSON as a JSON.net JSObject.

You need either

var responseJSON = JsonConvert.DeserializeObject<SomeObject>(responseString);

or

dynamic responseJSON = JsonConvert.DeserializeObject(responseString);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.