【发布时间】:2019-01-31 23:17:46
【问题描述】:
我得到的 json 不适合填充 datagridview(我认为)。我试图利用通过搜索得到的答案,但我仍然没有设法解决这个问题。
这就是我获取 json 的方式。
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["apikey"] = "my apikey";
string destination = @"http://www.";
var response = client.UploadValues(destination, values);
string responseString = Encoding.Default.GetString(response);
这就是我返回并放入 responseString 的内容。
{"error":"","return":{"key":"value","key":"value","key":"value"}}
以及填充datagridview 的最终代码。
var result = JsonConvert.DeserializeObject<List<JsonResult>>(responseString);
dataGridView1b.DataSource = result;
当我运行此代码时,会出现以下错误:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object
(e.g. {"name":"value"}) into
typeSystem.Collections.Generic.List`1[MarkkarteringMonitoring.JsonResult]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'error', line 1, position 9.'
但是,如果我使用下面的代码更改“responseString”中的 json,则一切正常,datagridview 将被填充。
responseString = "[{\"key\":\"value\",\"key\":\"value\",\"key\":\"value\"}]";
那么,我怎样才能让我的 json 自动更改并使用它来填充我的 datagridview。
【问题讨论】:
-
@vikscool - 这可能是因为我缺乏技能,但我不知道如何将其用于解决我的问题。
-
根据
Newtonsoft的错误输出,您正在尝试将Object反序列化为Array,根据输入源这是不可能的。因此,我给您的链接将帮助您识别responseString类型,如果它不是数组,您可以将其反序列化为一个对象,然后将其传递到List<JsonResult>的新列表中:var result = JsonConvert.DeserializeObject<JsonResult>(responseString);然后var resultList = (new List<JsonResult>()).Add(result);之后使用resultList作为您的数据源。 -
@vikscool - 我正在尝试,但我在下面看到一条红色曲线:
var resultList = (new List<JsonResult>()).Add(result);
标签: c# json datagridview