如何更改json,以便可以使用它填充datagridview

时间:2019-01-31 10:34:56

标签: c# json datagridview

我得到的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。

1 个答案:

答案 0 :(得分:2)

Newtonsoft试图告诉您的是,它无法将您的JSON Object转换为JSON Array

从您的Json响应中可以看到,您收到的JSON字符串为:

{"error":"","return":{"key":"value","key":"value","key":"value"}}

因此,到目前为止,您的代码中发生了两件事:

  1. responseString中收到的字符串显然是Object,而不是Array
  2. 可序列化的JsonResult属性位于上述 JSON字符串(如果我认为正确的话, )中的return键。.

因此,我们可以做的是将字符串解析为JObject使用Newtonsoft.Json.Linq 扩展名),然后在字符串中获取return令牌值并将其解析为JsonResult对象/数组。

var jobj = JsonConvert.DeserializeObject<JObject>(responseString);
var jsString = jobj["return "].ToString(); //here you have to make sure that the key name is specified correctly.
var token = JToken.Parse(jsString);
//now determine wither the recieved string is an object or an array
if (token is JArray)
{
     var results = token.ToObject<List<JsonResult>>();
     dataGridView1b.DataSource = results;
}
else if (token is JObject)
{
    var result = token.ToObject<JsonResult>();
    var results = new List<JsonResult>();
    results.Add(result);
    dataGridView1b.DataSource = results;
}        
相关问题