I am trying to serialize and deserialize a list of objects. First I generate the list:
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();
}
}
}
Then I serialize it and deserialize it:
var json_serializer = new JavaScriptSerializer();
var json = json_serializer.Serialize(groups);
List<AssetGroup> routes_list =(List<AssetGroup>)json_serializer.DeserializeObject(json);
However I get following error: System.InvalidCastException: 'Unable to cast object of type 'System.Object[]' to type 'System.Collections.Generic.List`1[CopyToCosmosDB.AssetGroup]'.'
I have following models:
[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; }
}
Ohh dear. Seemed there is another method Deserialize that does the task, and not DeserializeObject:
var json_serializer = new JavaScriptSerializer();
var json = json_serializer.Serialize(report);
Report routes_list =(Report)json_serializer.Deserialize<Report>(json);
Thanks for your help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.