【发布时间】:2018-05-23 23:28:00
【问题描述】:
我有以下代码:
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);
responseString 正确返回,但我正在尝试将其转换为对象,以便我可以使用返回值做更高级的事情。
问题是,C#/Visual Studio 抱怨 responseJSON.value 没有值(在异步操作完成之前它没有值)
我该如何解决这个问题?
【问题讨论】:
-
您正试图反序列化为
object,这可能是问题所在。函数的异步部分比这更早完成 -
您可能想要
JObject.Parse(responseJson),或者您可能想要创建一个表示 json 架构并反序列化为该特定类型的类。 -
如果没有可用的具体类,可以反序列化为动态
-
可以直接使用ReadAsAsync返回一个实例吗?例如。
var response = await response.Content.ReadAsAsync<MyClass>();
标签: c# json type-conversion deserialization