我正在使用与第三方 REST API 接口的 JSON.NET 开发 ASP.NET 应用程序。API 以以下格式返回 JSON:
[
{
user: {
id: 12345,
first_name: "John",
last_name: "Smith",
created_at: "11/12/13Z00:00:00"
}
},
{
user: {
id: 12346,
first_name: "Bob",
last_name: "Adams",
created_at: "12/12/13Z00:00:00"
}
}
]
该user
字段是多余的,但我无法控制 API,所以我必须忍受它。我目前正在使用以下代码来反序列化 JSON:
// Deserialize
var responseBody = JsonConvert.DeserializeObject<IEnumerable<UserWrapper>>(responseString);
// Access Properties
foreach (var userWrapper in responseBody)
{
var firstName = userWrapper.User.FirstName
}
// Model classes
public class UserWrapper
{
[JsonProperty(PropertyName = "user")]
public User User { get; set; }
}
public class User
{
[JsonProperty(PropertyName = "id")]
public string ID { get; set; }
[JsonProperty(PropertyName = "first_name")]
public string FirstName { get; set; }
[JsonProperty(PropertyName = "last_name")]
public string LastName { get; set; }
[JsonProperty(PropertyName = "created_at")]
public DateTime CreatedAt { get; set; }
}
拥有包装类有点难看。所以我的问题是:
有没有办法使用 JSON.NET 消除包装类?