【问题标题】:Serializing and deserializing complex objects序列化和反序列化复杂对象
【发布时间】:2018-10-11 17:27:29
【问题描述】:

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

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; }
}

【问题讨论】:

  • 尝试使用数组而不是列表:AssetGroup[] routes_list =(AssetGroup[])json_serializer.DeserializeObject(json);
  • 感谢您的回复。几乎相同的错误消息:System.InvalidCastException: 'Unable to cast object of type 'System.Object[]' to type 'CopyToCosmosDB.AssetGroup[]'。'
  • 它是否适用于没有强制转换的“var”?
  • 确实如此,但没有输入任何内容,所有属性都表示为键/值对。

标签: c# c#-4.0


【解决方案1】:

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

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

感谢您的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多