首页 > 解决方案 > JsonConvert.DeserializeObject 抛出无法加载文件或程序集'System.ComponentModel.Annotations,版本 = 4.3.0.0,文化

问题描述

string jsonDoc = @"{
    ""pricingDetails"": [{
            ""pricingStrategyId"": 1,
            ""pricingStrategy"": {
                ""id"": 1,
                ""name"": ""PREPAY_FIXED"",
                ""displayText"": ""Prepay fixed"",
                ""description"": ""Pay onsite a fixed price at entry.""
            },
            ""siteId"": 262,
            ""site"": {
                ""id"": 262,
                ""buildingId"": 64,
                ""siteName"": ""Test Site"",
                ""siteDescription"": ""test1"",
                ""isListed"": null,
                ""listedDateTime"": null,
                ""siteAfterHoursInstructions"": null,
                ""archiveDateTime"": null,
                ""archivedBy"": null,
                ""createdDateTime"": ""2019-04-09T00:00:00"",
                ""modifyDateTime"": ""2019-04-09T14:59:54.87"",
                ""statusId"": 5,
                ""siteMaxHeight"": ""2.1"",
                ""businessRegistrationId"": ""2019-105A110BU69L64B262"",
                ""businessAbnOracnNumber"": ""48 110 366 946"",
                ""businessPhoneNumber"": ""02 9017 1292"",
                ""businessFaxNumber"": """",
                ""bankAccountName"": null,
                ""bankAccountNumber"": null,
                ""bankBsbnumber"": null,
                ""bankEmailAddresses"": null,
                ""physicalAddressLine2"": """",
                ""physicalAddressSuburb"": ""Sydney"",
                ""physicalAddressState"": ""NSW"",
                ""physicalAddressPostcode"": 2000,
                ""postalAddressLine2"": """",
                ""postalAddressSuburb"": ""Sydney"",
                ""postalAddressState"": ""NSW"",
                ""postalAddressPostcode"": 2000,
                ""entryAddressLine2"": null,
                ""exitAddressLine2"": null,
                ""bankReferenceNo"": null,
                ""isGstregistered"": null,
                ""refParentBankDets"": false,
                ""canTakePayments"": false,
                ""siteOpenTime"": 60,
                ""siteCloseTime"": 1260,
                ""siteAccessOpenTime"": 360,
                ""siteAccessCloseTime"": 1080,
                ""occupiedTypeId"": 2,
                ""siteNotes"": null,
                ""securityType"": true,
                ""keyDelivery"": 3,
                ""keyInstrPickup"": null,
                ""keyInstrReturn"": null,
                ""smartCmsgLine1"": null,
                ""smartCmsgLine2"": null,
                ""instrGracePeriod"": null,
                ""instrOverstay"": null,
                ""isUnusedBay"": false,
                ""navStatusId"": 0,
                ""navErrorMsg"": null,
                ""priorityPass"": null,
                ""siteCommision"": 0,
                ""entryGracePeriod"": null,
                ""exitGracePeriod"": null,
                ""bookableDays"": null,
                ""checkQuota"": null,
                ""totalSpaces"": null
            },
            ""days"": 31,
            ""entryTimeOffset"": 360,
            ""exitTimeOffset"": 1080,
            ""price"": 7.00
        }
    ],
    ""relatedDevices"": [{
            ""id"": 15,
            ""siteId"": 262,
            ""roleId"": 2,
            ""role"": {
                ""id"": 2,
                ""name"": ""SC"",
                ""description"": ""Display device""
            },
            ""sideId"": 1,
            ""side"": {
                ""id"": 1,
                ""name"": ""IN""
            },
            ""lane"": 1,
            ""deviceGroup"": ""Live""
        }, {
            ""id"": 17,
            ""siteId"": 262,
            ""uid"": ""synorb1-exit1-ptg"",
            ""roleId"": 4,
            ""role"": {
                ""id"": 4,
                ""name"": ""PTG"",
                ""description"": ""Payment device""
            },
            ""sideId"": 1,
            ""side"": {
                ""id"": 1,
                ""name"": ""IN""
            },
            ""lane"": 1,
            ""deviceGroup"": ""Live""
        }
    ]
}
"
var obj = JsonConvert.DeserializeObject<ParkingOfferDetailsDTO>(jsonDoc);

==================================

public class ParkingOfferDetailsDTO
    {
        public List<CasualParkingPricingDetailsVM> PricingDetails { get; set; }

        public List<AccessDeviceVM> RelatedDevices { get; set; }
    }

    public class CasualParkingPricingDetailsVM
    {
        public int PricingStrategyId { get; set; }
        public virtual CasualParkingPricingStrategyVM PricingStrategy { get; set; }
        public int SiteId { get; set; }
        public virtual SitesVM Site { get; set; }
        // Enum.Days | 
        public int Days { get; set; }
        public int? EntryTimeOffset { get; set; }
        public int? ExitTimeOffset { get; set; }
        public decimal Price { get; set; }
    }

    public class CasualParkingPricingStrategyVM
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string DisplayText { get; set; }
        public string Description { get; set; }
    }

    public class SitesVM
    {
        public SitesVM()
        {
            //Bookings = new HashSet<Bookings>();
            //InventoryEntityRelationship = new HashSet<InventoryEntityRelationship>();
            //ParkingTypes = new HashSet<ParkingTypes>();
            //SiteLicenses = new HashSet<SiteLicenses>();
            //SiteTimeZones = new HashSet<SiteTimeZonesVM>();
            //Spaces = new HashSet<Spaces>();
        }

        public int Id { get; set; }
        public int BuildingId { get; set; }
        public string SiteName { get; set; }
        //public string Photos { get; set; }
        //public bool? HasOnSiteStaff { get; set; }
        //public string OnSiteStaffNotes { get; set; }
        public string SiteDescription { get; set; }
        public bool? IsListed { get; set; }
        public DateTime? ListedDateTime { get; set; }
        public string SiteAfterHoursInstructions { get; set; }
        public DateTime? ArchiveDateTime { get; set; }
        public string ArchivedBy { get; set; }
        public string CreatedBy { get; set; }
        public DateTime CreatedDateTime { get; set; }
        public string ModifiedBy { get; set; }
        public DateTime ModifyDateTime { get; set; }
        public int StatusId { get; set; }
        public string SiteMaxHeight { get; set; }
        public string BusinessName { get; set; }
        public string BusinessRegistrationId { get; set; }
        public string BusinessAbnOracnNumber { get; set; }
        public string BusinessPhoneNumber { get; set; }
        public string BusinessEmail { get; set; }
        public string BusinessFaxNumber { get; set; }
        public string BankAccountName { get; set; }
        public string BankAccountNumber { get; set; }
        public string BankBsbnumber { get; set; }
        public string BankEmailAddresses { get; set; }
        public string PhysicalAddressLine1 { get; set; }
        public string PhysicalAddressLine2 { get; set; }
        public string PhysicalAddressSuburb { get; set; }
        public string PhysicalAddressState { get; set; }
        public int PhysicalAddressPostcode { get; set; }
        public string PostalAddressLine1 { get; set; }
        public string PostalAddressLine2 { get; set; }
        public string PostalAddressSuburb { get; set; }
        public string PostalAddressState { get; set; }
        public int? PostalAddressPostcode { get; set; }
        public string EntryAddressLine2 { get; set; }
        public string ExitAddressLine2 { get; set; }
        public string BankReferenceNo { get; set; }
        public bool? IsGstregistered { get; set; }
        public bool RefParentBankDets { get; set; }
        public bool CanTakePayments { get; set; }
        public short? SiteOpenTime { get; set; }
        public short? SiteCloseTime { get; set; }
        public short? SiteAccessOpenTime { get; set; }
        public short? SiteAccessCloseTime { get; set; }
        public int OccupiedTypeId { get; set; }
        public string SiteNotes { get; set; }
        public bool SecurityType { get; set; }
        public int? KeyDelivery { get; set; }
        public string KeyInstrPickup { get; set; }
        public string KeyInstrReturn { get; set; }
        public string SmartCmsgLine1 { get; set; }
        public string SmartCmsgLine2 { get; set; }
        public string InstrGracePeriod { get; set; }
        public string InstrOverstay { get; set; }
        public bool IsUnusedBay { get; set; }
        public byte NavStatusId { get; set; }
        public string NavErrorMsg { get; set; }
        public string EntryAddressLine1 { get; set; }
        public string EntryAddressSuburb { get; set; }
        public string EntryAddressState { get; set; }
        public int? EntryAddressPostcode { get; set; }
        public string ExitAddressLine1 { get; set; }
        public string ExitAddressSuburb { get; set; }
        public string ExitAddressState { get; set; }
        public int? ExitAddressPostcode { get; set; }
        public bool? IsPublicSearchable { get; set; }
        public string PriorityPass { get; set; }
        public float SiteCommision { get; set; }
        public short? EntryGracePeriod { get; set; }
        public short? ExitGracePeriod { get; set; }
        public int? BookableDays { get; set; }
        public bool? CheckQuota { get; set; }
        public int? TotalSpaces { get; set; }

        //public virtual Buildings Building { get; set; }
        //public virtual RefNavStatus NavStatus { get; set; }
        //public virtual RefStatus Status { get; set; }
        //public virtual ICollection<Bookings> Bookings { get; set; }
        //public virtual ICollection<InventoryEntityRelationship> InventoryEntityRelationship { get; set; }
        //public virtual ICollection<ParkingTypes> ParkingTypes { get; set; }
        //public virtual ICollection<SiteLicenses> SiteLicenses { get; set; }
        //public virtual ICollection<SiteTimeZonesVM> SiteTimeZones { get; set; }
        //public virtual ICollection<Spaces> Spaces { get; set; }
    }

public class AccessDeviceVM
    {
        public int Id { get; set; }
        [Required]
        public int SiteId { get; set; }
        [Required]
        public string UID { get; set; }
        [Required]
        public int RoleId { get; set; }
        public AccessDeviceRoleVM Role { get; set; }

        [Required]
        public int SideId { get; set; }
        public AccessDeviceSideVM Side { get; set; }

        [Required]
        public int Lane { get; set; }
        [Required]
        public string DeviceGroup { get; set; }
    }

 public class AccessDeviceRoleVM
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }

    public class AccessDeviceSideVM
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

================ 我正在尝试将 JSON 字符串反序列化为嵌套对象。但是,它会导致异常。对我来说,例外看起来无关紧要。

上面我分享了 JSON 和 C# 类结构。我正在尝试反序列化 JSON,但它抛出“无法加载文件或程序集'System.ComponentModel.Annotations,异常......”

我也尝试过使用简单的对象结构和 JSON,它有效。

标签: c#json

解决方案


因此,如前所述,异常是无关紧要的(没有帮助)。这是我调试此问题的方法。

1)添加错误处理程序

// Created a JsonSerializerSettings and passed it to DeserializeObject

var jsonSettings = new JsonSerializerSettings { Error = ErrorHandler };
JsonConvert.DeserializeObject<ParkingOfferDetailsDTO>(responseJson, jsonSettings);

/// Actual handler method
        List<string> errors = new List<string>();
        private void ErrorHandler(object sender, ErrorEventArgs e)
        {
            errors.Add(e.ErrorContext.Error.Message);
            e.ErrorContext.Handled = true;
        }

这有两个方面的帮助,1)没有抛出异常,但相同的错误(异常)被传递给错误处理程序。2) 返回(不完整的)序列化对象。这指出了对象序列化的哪一部分导致了异常。

现在在我的代码/模型中发布。我在某些属性上有 [Required] 属性。不知道为什么,但这导致了反序列化错误。


推荐阅读