简体   繁体   English

将json字符串反序列化为C#中的对象变量

[英]Deserialize a json string to an object variable in C#

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. responseString可以正确返回,但是我正在尝试将其转换为对象,因此我可以使用返回值做更多高级的事情。

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) 问题是,C#/ Visual Studio抱怨responseJSON.value没有值(直到Async操作完成,该值才出现)

How do I get around this problem? 我该如何解决这个问题?

var responseJSON = JsonConvert.DeserializeObject(responseString);

creates responseJSON as a JSON.net JSObject. 创建responseJSON作为JSON.net JSObject。

You need either 你需要

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

or 要么

dynamic responseJSON = JsonConvert.DeserializeObject(responseString);

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

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