[英]Problem deserializing and object using json.net
USing json.net to deserialize json to a list. 使用json.net将json反序列化为列表。 My issue is that I am getting the following message: 我的问题是我收到以下消息:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: [. Newtonsoft.Json.JsonReaderException:'解析值时遇到意外字符:[。 Path 'data', line 1, position 9.' 路径“数据”,第1行,位置9。”
My code looks like this: 我的代码如下所示:
Dictionary<string, string> JSONObj = JsonConvert.DeserializeObject<Dictionary<string, string>> (response.Content.ToString());
and... 和...
internal class Projects
{
internal object id;
internal string gid;
internal string name;
internal string resource_type;
}
response.Content.ToString() looks like this: response.Content.ToString()看起来像这样:
{ "data": [{ "id": 123456, "gid": "789", "name": "Tooling - Start tool", "resource_type": "project" }, { "id": 123456, "gid": "789", "name": "Hold for Details", "resource_type": "project" }] } {“ data”:[{“ id”:123456,“ gid”:“ 789”,“ name”:“工具-启动工具”,“ resource_type”:“项目”},{“ id”:123456,“ gid “:” 789“,” name“:”保留详细信息“,” resource_type“:”项目“}]}
My json validates. 我的json验证。 I am certain that it is the formatting of the json but I do not understand enough to understand what is wrong. 我敢肯定,这是json的格式,但是我对理解错误的理解还不够。 What is wrong with my approach? 我的方法有什么问题? How do I get this formatted data to concert to a List of Projects? 如何获取格式化的数据以与项目列表协调一致?
According to the JSON, there's some root object ("data"), so your model should look like this: 根据JSON,有一些根对象(“数据”),因此您的模型应如下所示:
public class Project
{
public int id { get; set; }
public string gid { get; set; }
public string name { get; set; }
public string resource_type { get; set; }
}
public class RootObject
{
public List<Project> data { get; set; }
}
Then for parsing your code also changes: 然后用于解析您的代码也将更改:
var JSONObj = JsonConvert.DeserializeObject<RootObject>(response);
I'd also suggest thinking for a second about class name - your class is actually only one Project
, not any group/collection of Projects
. 我也建议想了约类名第二-你的类实际上是只有一个Project
,不是任何组/集合Projects
。
Also setting type of id
to object
looks like adding unnecessary overhead - it can be simply int
/ long
. 另外,将id
类型设置为object
似乎会增加不必要的开销-它可以简单地为int
/ long
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.