我被 Json.NET 库及其 DeserializeObject 方法困住了。文档不太清楚这里可能发生的事情,所以如果有人能解释如何将 JSON 反序列化为用户对象列表,我将不胜感激。
我正在尝试反序列化这个 JSON
[
{"userid":"0",
"listid":1,
"lastname":"Mann",
"inplace":true,
"xpos":428,
"ypos":111
},
{"userid":"1",
"listid":1,
"lastname":"Parker",
"inplace":true,
"xpos":334,
"ypos":154
},
{"userid":"2",
"listid":1,
"lastname":"Terry",
"inplace":true,
"xpos":513,
"ypos":160
}
]
进入用户对象
[JsonObject(MemberSerialization.OptIn)]
public class User
{
[JsonProperty(PropertyName = "userid")]
public string userid { get; set; }
[JsonProperty(PropertyName = "listid")]
public int listid { get; set; }
[JsonProperty(PropertyName = "lastname")]
public string lastname { get; set; }
[JsonProperty(PropertyName = "inplace")]
public bool inplace { get; set; }
[JsonProperty(PropertyName = "xpos")]
public int xpos { get; set; }
[JsonProperty(PropertyName = "ypos")]
public int ypos { get; set; }
public User()
{
}
}
使用
List<User> users = JsonConvert.DeserializeObject<List<User>>(jsonUsers);
没有成功。没有收到任何错误,也没有用户。JsonConvert.DeserializeObject 只是默默地死去。
我尝试创建模型并使用该 JSON 字符串执行 SerializeObject 和 DeserializeObject,但结果相同,没有错误,没有结果。
我什至尝试通过 serializersettings 以找出问题所在,但也没有错误
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Error += delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args) {
errorList.Add(args.ErrorContext.Error.Message);
};
List<User> users = JsonConvert.DeserializeObject<List<User>>(jsonUsers, settings);
当我尝试查看反序列化期间发生了什么时,我注意到上下文没有初始化?!
public class User
{
...
[OnDeserializing]
internal void OnDeserializing(StreamingContext context) {
}
}
我在这里做错了什么?以及如何将其反序列化为用户列表?