使用 Json.NET 将 JSON 反序列化为对象 [英] Deserializing JSON into an object with Json.NET
问题描述
我正在尝试使用新的 StackOverflow API一>.不幸的是,我的 JSON 有点弱,所以我需要一些帮助.
I'm playing a little bit with the new StackOverflow 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
属性装饰的对象中:
into an object which I've decorated with JsonProperty
attributes:
[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; }
...
}
我收到以下异常:
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?
提前致谢!
推荐答案
正如 Alexandre Jasmin 在您的问题评论中所说,生成的 JSON 对您正在尝试的实际 User
对象进行了包装反序列化.
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!
这篇关于使用 Json.NET 将 JSON 反序列化为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!