c# - 如何直接反序列化来自web api的json数据

标签 c# json

我试图直接反序列化来自Web Api的JSON数据。但它抛出错误:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TestMvc.Controllers.HomeController+TestJson]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

我的代码:

  public class TestJson
    {
        public string thing1
        {
            get;
            set;
        }

        public string thing2
        {
            get;
            set;
        }
    }

  using (WebClient wc = new WebClient())
        {
            var json = wc.DownloadString("http://localhost:43560/api/carvalues");

           List <TestJson> exam = new List<TestJson>();

           exam = JsonConvert.DeserializeObject<List<TestJson>>(json);

        }

json数据示例

{"thing1":"first thing","thing2":"second thing"}

我的目标是如何直接反序列化来自 WebAPI 的数据。我正在使用 Newtonsoft.Json 进行反序列化。

最佳答案

在这种情况下使用它而不使用列表

var exam = new TestJson();    
exam = JsonConvert.DeserializeObject<TestJson>(json);

关于c# - 如何直接反序列化来自web api的json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39276124/

相关文章:

javascript - 使用 JSON 文件动态更改图像内容?

c# - 当我显示新表单时,控件呈白色

C# volatile 和 interlocked 如何影响 cpu 缓存

c# - 在 MVC 3 中创建自定义数据注释验证

c# - 带有企业应用程序 block 的自定义跟踪监听器

c# - RegEx.Replace 但排除 html 标签内的匹配项?

java - java对象转json

c# - 尝试使用 AJAX 和 JQuery 将 JSON 对象传递给 C#

java - Web 服务器可以在没有请求的情况下将数据发送到桌面应用程序吗?

java - Spring @RequestBody 覆盖