JSON反序列化到一个对象Json.NET
我打一点点用新的计算器API 。不幸的是,我的JSON是有点弱,所以我需要一些帮助。
I'm playing a little bit with the new * API. Unfortunately, my JSON is a bit weak, so I need some help.
我想反序列化这个JSON的用户:
I'm trying to deserialize this JSON of a User:
{"user":{
"user_id": 1,
"user_type": "moderator",
"creation_date": 1217514151,
"display_name": "Jeff Atwood",
...
"accept_rate": 100
}}
到我已经装饰了 JsonProperty
一个对象的属性:
[JsonObject(MemberSerialization.OptIn)]
public class User
{
[JsonProperty("user_id", Required = Required.Always)]
public virtual long UserId { get; set; }
[JsonProperty("display_name", Required = Required.Always)]
public virtual string Name { get; set; }
...
}
我得到以下异常:
I get the following exception:
Newtonsoft.Json.JsonSerializationException: 必需属性USER_ID'未找到 在JSON。
Newtonsoft.Json.JsonSerializationException: Required property 'user_id' not found in JSON.
这是因为JSON对象是一个数组?如果是这样,我怎么能反序列化到一个User对象?
Is this because the JSON object is an array? If so, how can I deserialize it to the one User object?
在此先感谢!
由于亚历山大茉莉在你的问题的评论说,由此产生的JSON有各地的实际用户一个包装
对象你要反序列化。
As Alexandre Jasmin said in the comments of your question, the resulting JSON has a wrapper around the actual User
object you're trying to deserialize.
一个变通办法将话说回来包装类:
A work-around would be having said wrapper class:
public class UserResults
{
public User user { get; set; }
}
然后反序列化将工作:
Then the deserialization will work:
using (var sr = new StringReader(json))
using (var jr = new JsonTextReader(sr))
{
var js = new JsonSerializer();
var u = js.Deserialize<UserResults>(jr);
Console.WriteLine(u.user.display_name);
}
将有这个包装,如未来的元数据属性响应时间戳记,所以它不是一个坏主意,用它!
There will be future metadata properties on this wrapper, e.g. response timestamp, so it's not a bad idea to use it!