[英]C# - Cannot deserialize the current JSON array
I have this code:我有这个代码:
string json2 = vc.Request(model.uri + "?fields=uri,transcode.status", "GET");
var deserial = JsonConvert.DeserializeObject<Dictionary<string, object>>(json2);
var transcode = deserial["transcode"];
var serial = JsonConvert.SerializeObject(transcode);
var deserial2 = JsonConvert.DeserializeObject<Dictionary<string, object>>(serial);
var upstatus = deserial2["status"].ToString();
The json I get from the server is:我从服务器得到的 json 是:
{
"uri": "/videos/262240241",
"transcode": {
"status": "in_progress"
}
}
When running it on VS2017, it works.在 VS2017 上运行它时,它可以工作。
But on VS2010 I get the following error:但是在 VS2010 上,我收到以下错误:
Cannot deserialize the current JSON array (eg [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly.
无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' 因为该类型需要 JSON 对象(例如 {"name ":"value"}) 正确反序列化。 To fix this error either change the JSON to a JSON object (eg {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (eg ICollection, IList) like List that can be deserialized from a JSON array.
要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以从 JSON 数组反序列化。 JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
JsonArrayAttribute 也可以添加到类型以强制它从 JSON 数组反序列化。 Path '', line 1, position 1.
路径 '',第 1 行,位置 1。
I am using Newtonsoft.Json.我正在使用 Newtonsoft.Json。
Any idea?有什么想法吗?
Your received json data is not a Dictionary<string, object>
, it is a object您收到的 json 数据不是
Dictionary<string, object>
,它是一个对象
public class Transcode
{
public string status { get; set; }
}
public class VModel
{
public string uri { get; set; }
public Transcode transcode { get; set; }
}
You can use this object:你可以使用这个对象:
var deserial = JsonConvert.DeserializeObject<VModel>(json2);
instead of:而不是:
var deserial = JsonConvert.DeserializeObject<Dictionary<string, object>>(json2);
The best answer was deleted for some reason, so i'll post it:由于某种原因,最佳答案已被删除,因此我将其发布:
var deserial = JsonConvert.DeserializeObject<dynamic>(json2);
string upstatus = string.Empty;
upstatus = deserial.transcode.status.ToString();
If your model is not well defined or it is dynamic, then use:如果您的模型定义不明确或者是动态的,请使用:
var deserial = JsonConvert.DeserializeObject<dynamic>(json2);
or you can try to use:或者您可以尝试使用:
JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.