我有一个表单应该在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.
答案 0 :(得分:0)
很抱歉,我无法发表评论 - 但最近我想到的关于JSON序列化的一些事情是,有时发送到反序列化的对象是单个项目的形式,用于返回1个数据或作为返回1个以上数据的数组。 (参考:Deserializing JSON containing single or array of objects)
如果是,您可能需要摆脱动态。干杯