在将Cson数据转换为C#中的自定义模型时,我被困住了。 json数据的结构如下:
{
"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.
任何帮助将不胜感激。感谢
答案 0 :(得分:4)
albums
和photos
实际上是对象,而不是数组。
类似的东西:
public class FacebookModel
{
public string id { get; set; }
public AlbumModel albums { get; set; }
}
public class AlbumModel
{
public List<AlbumData> data {get;set;}
}
public class AlbumData
{
public string id { get; set; }
public string name { get; set; }
public PictureModel photos { get; set; }
}
public class PictureModel
{
public List<PictureData> data {get;set;}
}
public class PictureData
{
public string id { get; set; }
public string picture { get; set; }
}
等等。
答案 1 :(得分:-1)
此方法适用于任何复杂对象:
样品用法:
var complexObject = GetObjectFromJson&lt; YourComplexObject&gt;(jsonString,typeof(YourComplexObject));
using System.Runtime.Serialization.Json;
public static T GetObjectFromJson<T>(string jsonString, Type type)
{
var dcSerializer = new DataContractJsonSerializer(type);
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
return (T)dcSerializer.ReadObject(stream);
}
}