2017-11-22 15 views
0

JSON에 클래스를 serialize하려고하고 있는데 null 참조 예외가 발생했습니다. 왜이 문제를 해결할 수 있는지 이해할 수 있습니까?중첩 된 하위 클래스를 json으로 변환

몇 가지 중첩 클래스를 포함하는 클래스를 작성했습니다 (JSON 구조는 영국 통신사 DPD에서 제공함).

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

namespace DPDJSONLibrary 
{ 
    public class DPD_JSON 
    { 
    // insert shipment request 
     /// <summary> 
     /// Root Object. Insert Shipment Request 
     /// </summary> 
     public class IS 
     { 
      public string job_id { get; set; } 
      public bool collectionOnDelivery { get; set; } 
      public IS_Invoice invoice { get; set; } 
      public string collectionDate { get; set; } 
      public bool consolidate { get; set; } 
      public IS_Consignment consignment { get; set; } 
     } 
     public class IS_Address 
     { 
      public string addressId { get; set; } 
      public string countryCode { get; set; } 
      public string countryName { get; set; } 
      public string county { get; set; } 
      public string locality { get; set; } 
      public string organisation { get; set; } 
      public string postcode { get; set; } 
      public string street { get; set; } 
      public string town { get; set; } 
     } 
     public class IS_ContactDetails 
     { 
      public string contactName { get; set; } 
      public string telephone { get; set; } 
     } 
     public class IS_PickupLocation 
     { 
      public IS_Address address { get; set; } 
      public bool allowRemotePickup { get; set; } 
      public string pickupLocationCode { get; set; } 
     } 
     public class IS_NotificationDetails 
     { 
      public string email { get; set; } 
      public string mobile { get; set; } 
     } 
     public class IS_ParcelProduct 
     { 
      public string countryOfOrigin { get; set; } 
      public Int32 numberOfItems { get; set; } 
      public string productCode { get; set; } 
      public string productFabricContent { get; set; } 
      public string productHarmonisedCode { get; set; } 
      public string productItemsDescription { get; set; } 
      public string productTypeDescription { get; set; } 
      public decimal unitValue { get; set; } 
      public decimal unitWeight { get; set; } 
     } 

     public class IS_InvoiceItem 
     { 
      public string countryOfOrigin { get; set; } 
      public string itemCode { get; set; } 
      public string itemDescription { get; set; } 
      public int numberOfItems { get; set; } 
      public decimal unitValue { get; set; } 
     } 

     public class IS_InvoiceBillingDetails 
     { 
      public IS_Address address { get; set; } 
      public IS_ContactDetails contactDetails { get; set; } 
      public string vatNumber { get; set; } 
     } 

     public class IS_Invoice 
     { 
      public string countryOfOrigin { get; set; } 
      public IS_InvoiceBillingDetails invoiceBillingDetails { get; set; } 
      public string invoiceCustomsNumber { get; set; } 
      public string invoiceExportReason { get; set; } 
      public bool invoiceIsDeclared { get; set; } 
      public IS_InvoiceItem invoiceItem { get; set; } 
      public string invoiceTermsOfDelivery { get; set; } 
      public int invoiceType { get; set; } 
      public int totalItems { get; set; } 
      public decimal totalValue { get; set; } 
      public decimal totalWeight { get; set; } 
     } 

     public class IS_DeliveryDetails 
     { 
      public IS_Address address { get; set; } 
      public IS_ContactDetails contactDetails { get; set; } 
      public IS_NotificationDetails notificationDetails { get; set; } 
      public IS_PickupLocation deliveryDetails { get; set; } 
     } 

     public class IS_CollectionDetails 
     { 
      public IS_Address address { get; set; } 
      public IS_ContactDetails contactDetails { get; set; } 
     } 

     public class IS_Parcels 
     { 
      public bool isVoided { get; set; } 
      public string labelNumber { get; set; } 
      public int packageNumber { get; set; } 
      public string parcelNumber { get; set; } 
      public IS_ParcelProduct parcelProduct { get; set; } 
      public string parcelnetBarcode { get; set; } 
      public string parcelnetData { get; set; } 
      public string parcelnetLabelNumber { get; set; } 
     } 

     public class IS_Consignment 
     { 
      public IS_CollectionDetails collectionDetails { get; set; } 
      public string consignmentNumber { get; set; } 
      public string consignmentRef { get; set; } 
      public decimal? customsValue { get; set; } 
      public IS_DeliveryDetails deliveryDetails { get; set; } 
      public string deliveryInstructions { get; set; } 
      public bool liability { get; set; } 
      public decimal liabilityValue { get; set; } 
      public string networkCode { get; set; } 
      public int numberOfParcels { get; set; } 
      public IS_Parcels parcel { get; set; } 
      public string parceldescription { get; set; } 
      public string shippingRef1 { get; set; } 
      public string shippingRef2 { get; set; } 
      public string shippingRef3 { get; set; } 
      public decimal totalWeight { get; set; } 
     } 
    } 
} 

는 내가 코드에서 값을 할당 공용 변수를 포함하는 다른 클래스, 내 JSON 클래스를 인스턴스화하고 공용 변수에서 값을 가져 오도록하는 방법/기능을 가지고있다.

나는 라인에 널 참조 예외를 얻고있다 :

NewShipmentObject.consignment.consignmentNumber = null; 

오류가 읽

error System.NullReferenceException: Object reference not set to an instance of an object 

내가 호출하고있는 오류가 캠 방법은 다음과 같습니다 :

using System; 
using System.Text; 
using System.Net; 
// include 
using System.IO; 
using System.Web.UI.WebControls; 
using DPDJSONLibrary; 
using System.Web; 
using Newtonsoft.Json; 

namespace DPDAPILibrary 
{ 
    public class DPD_API 
    { 

     #region public class variables 
     public string BusinessUnit; 
     public string DeliveryDirection; 
     public string NumberOfParcels; 
     public string ShipmentType; 
     public string TotalWeight; 
     public string CollectionDate; 
     public string ColName; 
     public string ColPhone; 
     public string ColOrganisation; 
     public string ColCountryCode; 
     public string ColPostCode; 
     public string ColStreet; 
     public string ColLocality; 
     public string ColTown; 
     public string ColCounty; 
     public string DelName; 
     public string DelPhone; 
     public string DelOrganisation; 
     public string DelCountryCode; 
     public string DelPostcode; 
     public string DelStreet; 
     public string DelLocality; 
     public string DelTown; 
     public string DelCounty; 
     public string DelNotificationEmail; 
     public string DelNotificationMobile; 
     public string NetworkCode; 
     public string ShippingRef1; 
     public string ShippingRef2; 
     public string ShippingRef3; 
     public string CustomsValue; 
     public string DeliveryInstructions; 
     public string ParcelDescription; 
     public string LiabilityValue; 
     public string Liability; 
     #endregion 


     public Boolean insertShipment(out string JSONData) 
     { 
      try 
      { 
       DPD_JSON.IS NewShipmentObject = new DPD_JSON.IS(); 

       NewShipmentObject.job_id = null; 
       NewShipmentObject.collectionOnDelivery = false; 
       NewShipmentObject.invoice = null; 
       NewShipmentObject.collectionDate = CollectionDate; 
       NewShipmentObject.consolidate = false; 
       NewShipmentObject.consignment.consignmentNumber = null; 
       NewShipmentObject.consignment.consignmentRef = null; 
       NewShipmentObject.consignment.parcel = null; 

       NewShipmentObject.consignment.collectionDetails.contactDetails.contactName = ColName; 
       NewShipmentObject.consignment.collectionDetails.contactDetails.telephone = ColPhone; 
       NewShipmentObject.consignment.collectionDetails.address.organisation = ColOrganisation; 
       NewShipmentObject.consignment.collectionDetails.address.countryCode = ColCountryCode; 
       NewShipmentObject.consignment.collectionDetails.address.postcode = ColPostCode; 
       NewShipmentObject.consignment.collectionDetails.address.street = ColStreet; 
       NewShipmentObject.consignment.collectionDetails.address.locality = ColLocality; 
       NewShipmentObject.consignment.collectionDetails.address.town = ColTown; 
       NewShipmentObject.consignment.collectionDetails.address.county = ColCounty; 

       NewShipmentObject.consignment.deliveryDetails.contactDetails.contactName = ColName; 
       NewShipmentObject.consignment.deliveryDetails.contactDetails.telephone = DelPhone; 
       NewShipmentObject.consignment.deliveryDetails.address.organisation = DelOrganisation; 
       NewShipmentObject.consignment.deliveryDetails.address.countryCode = DelCountryCode; 
       NewShipmentObject.consignment.deliveryDetails.address.postcode = DelPostcode; 
       NewShipmentObject.consignment.deliveryDetails.address.street = DelStreet; 
       NewShipmentObject.consignment.deliveryDetails.address.locality = DelLocality; 
       NewShipmentObject.consignment.deliveryDetails.address.town = DelTown; 
       NewShipmentObject.consignment.deliveryDetails.address.county = DelCounty; 

       NewShipmentObject.consignment.deliveryDetails.notificationDetails.email = DelNotificationEmail; 
       NewShipmentObject.consignment.deliveryDetails.notificationDetails.mobile = DelNotificationMobile; 

       // default output value 
       JSONData = ""; 

       JSONData = Convert.ToString(JsonConvert.SerializeObject(NewShipmentObject)); 

      } 
      catch (Exception ex) 
      { 
       JSONData = Convert.ToString(ex); 
       return false; 
      } 
     } 
    } 
} 
+1

그것은 NewShipmentObject의 위탁 속성처럼 보인다는 null입니다. –

+0

왜 아래 표를 보냅니 까? –

답변

1

* 사용할 수 있기 전에 모든 개체 (하위 항목 포함)를 초기화해야합니다. 개체의 경우 null이됩니다. 즉, 대체와

NewShipmentObject.consignment.consignmentNumber = null; 

:

NewShipmentObject.consignment = new IS_Consignment(); 
NewShipmentObject.consignment.consignmentNumber = null; 

당신은 자신에게 입력을 많이 절약 할 수 있습니다 - 대신 각 필드의 라인 별 설정에, 당신이 그렇게 개체 이니셜 라이저 구문을 사용하여 수행 할 수 있습니다

var NewShipmentObject = new DPD_JSON.IS 
{ 
    job_id = null, 
    collectionOnDelivery = false, 
    consignment = new IS_Consignment 
    { 
     consignmentNumber = null, 
     ... more consignment settings here 
    } 
    ... etc. 
당신이 명시 적으로 기본값으로 초기화되지 않은 변수를 설정할 필요가 없습니다 주목해야한다

, 즉 두

,
job_id = null, 
collectionOnDelivery = false 

은 중복되는데, 이는 어떤 경우에도 기본값이어야하기 때문입니다.

* (이 초기화는 생성자에서 자동으로 수행되지 않는 한)