序列化和反序列化复杂对象

时间:2018-10-11 17:27:29

标签: c# c#-4.0

我正在尝试序列化和反序列化对象列表。首先,我生成列表:

var groups = db.AssetGroupList.ToList();

foreach(var group in groups)
{
   group.AssetSubGroupList = db.AssetSubGroupList.Where(p => p.AssetGroupId == group.AssetGroupId).ToList();
   foreach(var subGroup in group.AssetSubGroupList)
   {
      subGroup.AssetList = db.AssetList.Where(p => p.AssetSubGroupId == subGroup.AssetSubGroupId).ToList();                  
      foreach(var asset in subGroup.AssetList)
      {
         asset.ReportAsset = null;// db.ReportAssetList.Where(p => p.AssetId == asset.AssetId).FirstOrDefault();
      }
   }
}

然后我将其序列化并反序列化:

var json_serializer = new JavaScriptSerializer();
var json = json_serializer.Serialize(groups);
List<AssetGroup> routes_list =(List<AssetGroup>)json_serializer.DeserializeObject(json);

但是我得到以下错误: System.InvalidCastException:'无法将类型为'System.Object []'的对象转换为类型为'System.Collections.Generic.List`1 [CopyToCosmosDB.AssetGroup]'。”

我有以下型号:

[Table("AssetGroup")]
public class AssetGroup
{
    [Key]
    public int AssetGroupId { get; set; }

    public int Code { get; set; }

    public string Name { get; set; }

    [NotMapped]
    public List<AssetSubGroup> AssetSubGroupList { get; set; }
}


public class AssetSubGroup
{
    [Key]
    public int AssetSubGroupId { get; set; }

    [InverseProperty("AssetSubGroupList")]
    public int AssetGroupId { get; set; }

    public int Code { get; set; }

    public string Name { get; set; }

    [NotMapped]
    public List<Asset> AssetList { get; set; }
   }

[Table("Asset")]
public class Asset
{
    [Key]
     public int AssetId { get; set; }

    public int Code { get; set; }

    public string Name { get; set; }

    public int AssetSubGroupId { get; set; }

    [NotMapped]
    public ReportAsset ReportAsset { get; set; }
}

[Table("ReportAsset")]
public class ReportAsset
{
    [Key]
    public int ReportAssetId { get; set; }
    public decimal Rating { get; set; }
    public int ReportId { get; set; }


    public int AssetId { get; set; }
    public string Remark { get; set; }
    public DateTime? Updated { get; set; }

    //public Asset Asset { get; set; }
}

1 个答案:

答案 0 :(得分:0)

哦,亲爱的。似乎还有另一种方法Deserialize可以完成任务,而不是DeserializeObject:

var json_serializer = new JavaScriptSerializer();
var json = json_serializer.Serialize(report);
Report routes_list =(Report)json_serializer.Deserialize<Report>(json);

感谢您的帮助。