我在将json数据转换为C#中的自定义模型时遇到了困难。 JSON数据具有这样的结构象下面这样:将复杂的json对象反序列化为自定义数据模型c#
{
"id": "100002231955291",
"albums": {
"data": [
{
"id": "103570756393989",
"name": "xyz",
"photos": {
"data": [
{
"id": "707563939dsf89",
"picture": "htp:// ssdsome data"
},
{
"id": "7075dfsd6393989",
"picture": "htp:// ssdsome data"
},
............
..................... .. and so on ......
我试图代码反序列化上述JSON数据:
var parsed = JsonConvert.DeserializeObject<FacebookModel>(data.ToString());
但问题是rootObject还含有一些JSON数组,这是不能转换(反序列化)。我的模型(POCO类)是:
public class FacebookModel
{
public string id { get; set; }
List<AlbumModel> albums { get; set; }
}
public class AlbumModel
{
public string id { get; set; }
public string name { get; set; }
public List<PictureModel> photos { get; set; }
}
public class PictureModel
{
public string id { get; set; }
public string picture { get; set; }
}
错误:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Bricks.Common.CustomModels.PictureModel]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
任何帮助,将不胜感激。谢谢
一个不平凡的解决方案是实现自定义序列化。 –
所以没有办法用json属性或属性来解决这个问题? –
那么,它说有错误,那里设置属性,对吧? 当你说根对象有数组时,你是在谈论根级别上的匿名数组还是在根级别上使用名称的数组? 我会认为命名变量,本身,数组将很容易反序列化。只要让他们从List下载类型,将JSonObjectAttribute添加到类中,或者可能将属性添加到属性本身? –