【问题标题】:How to deserialize json data coming from web api directly如何直接反序列化来自 web api 的 json 数据
【发布时间】:2016-09-01 15:59:15
【问题描述】:

我正在尝试直接反序列化来自 Web Api 的 JSON 数据。但它是 throwinn 错误:

无法反序列化当前 JSON 对象(例如 {"name":"value"}) 输入类型 'System.Collections.Generic.List`1[TestMvc.Controllers.HomeController+TestJson]' 因为该类型需要一个 JSON 数组(例如 [1,2,3])来反序列化 正确。

我的代码:

  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 进行反序列化。

【问题讨论】:

    标签: c# json


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      示例 json 数据表明它只是响应中返回的一个对象,您期望该对象的数组/列表。

      修改 webapi 以返回列表而不是单个对象,它应该可以解决问题。

      【讨论】:

        【解决方案3】:

        你的 JSON 数据需要在数组中,像这样

        "data": [{
            "thing1": "first thing",
            "thing2": "second thing"
        }, {
            "thing1": "first thing",
            "thing2": "second thing"
        }, {
            "thing1": "first thing",
            "thing2": "second thing"
        }]
        

        或使用普通类,即特定于这种情况

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

        【讨论】:

          猜你喜欢
          • 2014-04-27
          • 1970-01-01
          • 1970-01-01
          • 2014-01-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多