[英]How to correctly deserialize nested object in array with Newtonsoft.Json?
I'm facing this json data:我正面临这个json数据:
{
"pagemeta": {
"slug": "/",
"title": "test",
"description": "test"
},
"navigationlinks": {
"links": [{
"navigationlink": {
"name": "Index.",
"url": "/"
}
}]
}
}
And both using HttpRespondeMessage.Content.ReadAsJsonAsync<T>();
并且都使用
HttpRespondeMessage.Content.ReadAsJsonAsync<T>();
or JsonConvert.DeserializeAnonymousType(jsonString, new MyClassToDeserializeInto())
Both parsings seem to function well, except when it comes to the objects inside the array "links"
.或
JsonConvert.DeserializeAnonymousType(jsonString, new MyClassToDeserializeInto())
两种JsonConvert.DeserializeAnonymousType(jsonString, new MyClassToDeserializeInto())
似乎都运行良好,除非涉及到数组"links"
的对象。
Those do get to become object in the array in class but all data is null
(both name
and url
like in this example).那些确实会成为类中数组中的对象,但所有数据都为
null
( name
和url
像本例中一样)。
Am I doing something wrong to don't get the json deserialized correctly?我做错了什么没有正确反序列化json吗?
Following are the classes that I use as the final target object:以下是我用作最终目标对象的类:
HomeData.cs HomeData.cs
public sealed class HomeData
{
[JsonProperty("pagemeta")]
public PageMeta PageMeta { get; set; }
[JsonProperty("navigationlinks")]
public NavigationLinks NavigationLinks { get; set; }
}
NavigationLinks.cs导航链接.cs
public class NavigationLinks
{
[JsonProperty("links")]
public NavigationLink[] Links { get; set; }
}
NavigationLink.cs导航链接.cs
public class NavigationLink
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
}
meanwhile the PageMeta.cs
does the data correctly.同时
PageMeta.cs
正确处理数据。
You have missed the Links class, and mark the Links class as JsonObject您错过了 Links 类,并将 Links 类标记为 JsonObject
public sealed class HomeData
{
[JsonProperty("pagemeta")]
public PageMeta PageMeta { get; set; }
[JsonProperty("navigationlinks")]
public NavigationLinks NavigationLinks { get; set; }
}
public class PageMeta
{
[JsonProperty("slug")]
public string Slug { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
}
public class NavigationLink
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
}
public class NavigationLinks
{
[JsonProperty("links")]
public Links[] Links { get; set; }
}
[JsonObject]
public class Links
{
[JsonProperty("navigationlink")]
public NavigationLink NavigationLink { get; set; }
}
And then use it like this :然后像这样使用它:
var homedata = JsonConvert.DeserializeAnonymousType(text, new HomeData());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.