use*_*258 7 serialization json.net
我遇到了Json.NET库及其DeserializeObject方法.文档对于这里可能发生的事情并不十分清楚,所以如果有人能够解释如何将JSON反序列化为User对象列表,我将不胜感激.
我正在尝试反序列化这个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
}
]
Run Code Online (Sandbox Code Playgroud)
进入用户对象
[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()
{
}
}
Run Code Online (Sandbox Code Playgroud)
运用
List<User> users = JsonConvert.DeserializeObject<List<User>>(jsonUsers);
Run Code Online (Sandbox Code Playgroud)
没有成功.没有任何错误,也没有用户.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);
Run Code Online (Sandbox Code Playgroud)
当我试图看到反序列化过程中发生了什么时,我注意到上下文没有被初始化?!
public class User
{
...
[OnDeserializing]
internal void OnDeserializing(StreamingContext context) {
}
}
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?我如何将其反序列化为用户列表?
我发现了什么问题.JSon.NET将我的整数从JSON反序列化到Int64而不是Int32,所以我把它放在long而且一切都按原样运行.
有没有办法指定我希望该属性反序列化为int?
| 归档时间: |
|
| 查看次数: |
14756 次 |
| 最近记录: |