【发布时间】:2014-01-19 08:21:42
【问题描述】:
在将 json 数据转换为 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数组,无法转换(Deserialize)。我的模型(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 添加到类中,或者可能将属性添加到属性本身?
-
我刚刚注意到“albums”有一个第一个对象,“data”所以在你的代码中它应该是类专辑{ List
data { get;放; } ; } ... 而不是你所拥有的,即 List 专辑。 -
尝试使用 Ilist
并获取列表中的第一项“Ilist[0]
标签: c# .net json json.net deserialization