【问题标题】:Deserializing an array of objects反序列化对象数组
【发布时间】:2020-07-15 19:12:13
【问题描述】:

我很难反序列化以下 JSON

[{"JobID": 397597,"CustomerId": "ENV"},
 {"JobID": 397694,"CustomerId": "UNI015"},
 {"JobID": 397836,"CustomerId": "AMA003"}]
JobData Class
   public class JobData
    {
        [JsonProperty("JobID")]
        public int JobID;
        [JsonProperty("CustomerId")]
        public string CustomerId;
    }
   

这是 REST 服务类

    public class RESTService
    {
        readonly HttpClient _client;

        public RESTService()
        {
            _client = new HttpClient();
        }

        public async Task<List<JobData>> GetJobData(string query)
        {
            List<JobData> jobData = null;
            try
            {
                var response = await _client.GetAsync(query);
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    jobData = JsonConvert.DeserializeObject<List<JobData>>(content);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\t\tERROR {0}", ex.Message);
            }

            return jobData;
        }
    }
}

我希望将 JSON 响应读入 Xamarin Listview,但未返回任何数据。内容变量返回一个有效的 JSON 字符串。

【问题讨论】:

标签: c# arrays json xamarin.forms.listview


【解决方案1】:

尝试在 Startup.cs 类中用services.AddNewtonsoftJson();配置它

其次,我将初始化 JobData。 var jobData = new List&lt;JobData&gt;(); 这比使用null 更好。

如果这不起作用,请调试程序并查看var content 包含的内容。如果您知道content 包含的内容,它可以让您走得更远。

【讨论】:

  • JsonConvert 来自 Newtonsoft
  • 这是 var 内容包含的内容 [0:] [{"JobID":397831,"CustomerId":"SELECT"},{"JobID":397613,"CustomerId":"SELECT" },{"JobID":397614,"CustomerId":"SELECT"}]
  • 使用 CustomerId 有问题。在您的问题中,您有不同的价值观。也可以试试jobData = (JsonConvert.DeserializeObject&lt;JobData[]&gt;(content)).ToList();
猜你喜欢
  • 1970-01-01
  • 2023-01-11
  • 2015-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多