2016-08-30 3 views
-3

asp.net mvc 5でjsonオブジェクトを作成しようとしています。 ここに私のコードです。しかし、これを実行すると、 "オブジェクト参照がオブジェクトのインスタンスに設定されていません"というメッセージが表示されます。これで私を助けてください。それは新しいPaymentAmountインスタンスに設定されていないので、感謝"オブジェクト参照がオブジェクトのインスタンスに設定されていない"を修正する方法

public ActionResult Test() 
    { 
     AmountTransaction amount = new AmountTransaction(); 
     amount.endUserId = "93786853033"; 
     amount.paymentAmount.chargingInformation.amount = "1"; 
     amount.paymentAmount.chargingInformation.code = "1"; 
     amount.paymentAmount.chargingInformation.currency = "AFA"; 
     amount.paymentAmount.chargingInformation.description = "charge it"; 
     amount.referenceCode = "1"; 
     amount.transactionStatus = "Charged"; 
     var javaScriptSerializer = new JavaScriptSerializer(); 
     string jsonString = javaScriptSerializer.Serialize(amount); 
     Console.WriteLine(jsonString); 
     return View(); 
    } 

と私のクラス

public class ChargingInformation 
{ 
    public string amount { get; set; } 
    public string code { get; set; } 
    public string currency { get; set; } 
    public string description { get; set; } 
} 

public class PaymentAmount 
{ 
    public ChargingInformation chargingInformation { get; set; } 
} 

public class AmountTransaction 
{ 
    public string endUserId { get; set; } 
    public PaymentAmount paymentAmount { get; set; } 
    public string referenceCode { get; set; } 
    public string transactionStatus { get; set; } 
} 

public class RootObject 
{ 
    public AmountTransaction amountTransaction { get; set; } 
} 
+0

例外をスローする行は指定していません。 'amount.paymentAmount.chargingInformation.amount =" 1 ";' paymentAmount'は 'null'なので、ヌルのプロパティに値を代入することはできません –

+0

正しいコードの例を教えてください。 –

+0

複製を読む!値を代入する前に 'paymentAmount' - ' amount.paymentAmount = new PaymentAmount(); 'を初期化する必要があります。 –

答えて

0

AmountTransactionのあなたpaymentAmountフィールドがnull参照を投げています。

同クラスのChargingInformationと同じです。

+0

あなたは正しいコードを教えてください。 –

+0

ありがとうございます。私はあなたの助けを借りてそれを修正しました;-) –

関連する問題