【问题标题】:With RestSharp, Newtonsoft.Json Cannot deserialize the current JSON array (e.g. [1,2,3])使用 RestSharp,Newtonsoft.Json 无法反序列化当前 JSON 数组(例如 [1,2,3])
【发布时间】:2019-06-12 07:14:59
【问题描述】:

我是 C# API 的新手...我使用 nodejs 服务器从 SQL 服务器获取数据以生成 json 创建了一个新服务器,我正在使用 RestSharp 使用 c# windows 应用程序创建一个自定义应用程序向服务器发送请求并收到一个使用 Newtonsoft 的响应我得到错误无法反序列化当前的 json 数组帮助我解决以下代码的问题

JSON

[[{"id":2000,"engine":1,"wheel":1,"ac":1,"nitro":1,"rim":1},{"id":2001,"engine":1,"wheel":1,"ac":1,"nitro":1,"rim":1}]]

代码

using RestSharp;
using Newtonsoft.Json;

private void Form1_Load(object sender, EventArgs e)
        {
            var client = new RestClient("http://localhost:8000/employees");
            var request = new RestRequest(Method.GET);
            IRestResponse response = client.Execute(request);
            var x = JsonConvert.DeserializeObject<RootObject>(response.Content);
            foreach (var player in x.Abbrecipes)
            {
                comboBox1.Items.Add(player.id);
            }
        }

public class Abbrecipe
        {
            public int id { get; set; }
            public int engine { get; set; }
            public int wheel { get; set; }
            public int ac { get; set; }
            public int nitro { get; set; }
            public int rim { get; set; }
        }
        public class RootObject
        {
            public List<Abbrecipe> Abbrecipes { get; set; }
        }

【问题讨论】:

  • 您是否看到您的 json 中的[] 太多了?
  • 您的 JSON 包含对象集合的集合,您需要反序列化为相同的集合。试试DeserializeObject&lt;List&lt;List&lt;RootObject&gt;&gt;&gt;(...)
  • 所以它在转换 json 时出现在服务器上的问题

标签: c# json json.net deserialization restsharp


【解决方案1】:

这是您当前情况的代码,作为使用 WebClient 而不是 RestClient 的方法:

private static Rootobject publicFeed;

    public static void Set()
    {
        publicFeed = new Rootobject();

        using (var client = new WebClient())
        {
            string result;
            try
            {
                result = client.DownloadString("your json");//configure json stringdata
            }
            catch (Exception)
            {
                Console.WriteLine("This application needs a valid internet connection, please try again.");
                result = null;
                return;
            }

            publicFeed = JsonConvert.DeserializeObject<Rootobject>(result);
        }
    }

【讨论】:

    猜你喜欢
    • 2014-03-20
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    相关资源
    最近更新 更多