【问题标题】:How to handle Newtonsoft.Json.JsonSerializationException?如何处理 Newtonsoft.Json.JsonSerializationException?
【发布时间】:2017-07-02 19:16:16
【问题描述】:

我有一个表单应该在 ListView 中显示返回的数据,JSON 格式的数据如下:

 [
  {
    "intel_content": "This intel is top secret.", 
    "intel_date": "2017-07-01T22:36:57.353345+00:00", 
    "intel_id": 3, 
    "intel_title": "2001 Intel", 
    "operation_id": 1, 
    "source_id": 1
 }, 
 {
    "intel_content": "This is another intel on the first operation. ", 
    "intel_date": "2017-07-01T22:35:35.720128+00:00", 
    "intel_id": 2, 
    "intel_title": "Intel 505", 
    "operation_id": 1, 
    "source_id": 1
 }
]

我尝试遍历从服务器返回的结果,但我似乎遇到了这个异常,我之前没有这个问题这是我的代码:

  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data;
  using System.Drawing;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  using System.Windows.Forms;
  using MetroFramework.Forms;
  using MetroFramework;
  using DalSoft.RestClient;
  using DalSoft.RestClient.Handlers;
  using System.Net;
  using Newtonsoft.Json;

 namespace IGIS_Committee
 {
public partial class Dashboard : MetroForm
{
    public Dashboard()
    {
        InitializeComponent();
    }
    public static long selectedItl = -1;

    private void Dashboard_Load(object sender, EventArgs e)
    {
        listIntels.Items.Clear();
        String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(Login.username + ":"+ Login.password));
        dynamic client = new RestClient("http://localhost:5000/api/v1/", new Dictionary<string, string> { { "Authorization", "Basic " + encoded } });
        getIntels(client);
    }
    public async void getIntels(dynamic client)
    {
        var result = await client.intels.Get();

        //dynamic dynamicObject = JsonConvert.DeserializeObject(result.ToString());

        // This is where the exception occurs

        foreach (var it in result)
        {
            ListViewItem itl = new ListViewItem(it.intel_id.ToString());
            itl.SubItems.Add(it.intel_title);
            itl.SubItems.Add(it.source_id.ToString());
            itl.SubItems.Add(it.intel_date.ToShortDateString());
            itl.SubItems.Add(it.operation_id.ToString());
            itl.SubItems.Add(it.intel_content);
            listIntels.Items.Add(itl);
        }
    }

    private void listIntels_DoubleClick(object sender, EventArgs e)
    {
        selectedItl = long.Parse(listIntels.SelectedItems[0].SubItems[0].Text);
        IntelDetail fm = new IntelDetail();
        fm.ShowDialog();
    }

    private void tlPost_Click(object sender, EventArgs e)
    {
        RateIntel fm = new RateIntel();
        fm.Show();
    }

    private void tlViewIntels_Click(object sender, EventArgs e)
    {
        CommitteeRatings fm = new CommitteeRatings();
        fm.Show();
    }

    private void tileLogout_Click(object sender, EventArgs e)
    {
        this.Close();
        Login fm = new Login();
        fm.Show();
    }
}
}

这是个例外:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current 
JSON object (e.g. {"name":"value"}) into type 
'System.Collections.IEnumerable' because the type requires a JSON array 
(e.g. [1,2,3]) to deserialize correctly.

【问题讨论】:

  • 请发布整个例外情况。
  • 理想情况下,您应该创建一个与您接收的数据相对应的类,而不是使用动态的。然后将您的 JSON 反序列化为 List&lt;myType&gt;。使用动态确实使事情变得复杂,因此除非完全必要,否则将其删除。
  • 我在整个项目中都使用了动态,如果我不改变一切就好了,我至少还有另外 10 个这样的表格@stybl
  • 按照您编写的方式,该程序很可能甚至无法正常运行。除非涉及演员阵容,否则无论如何您都需要该课程。我的建议是切换。它不仅可以解决您的问题,而且符合最佳实践。
  • 你想要一个动态沼泽。立即享受!

标签: c# json serialization


【解决方案1】:

抱歉,我无法发表评论——但我最近想到的关于 JSON 序列化的一些事情是,有时发送以进行反序列化的对象是以单个项目的形式返回 1 个数据或作为返回超过 1 个数据时的数组。 (参考:Deserializing JSON containing single or array of objects

如果是,您可能需要远离动态。干杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    相关资源
    最近更新 更多