我在將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添加到類中,或者可能將屬性添加到屬性本身? –