-1

i am trying to create a json object in asp.net mvc 5 . here is my code. but when i run this, it gives a message "object reference not set to an instance of an object". please help me with this. thanks

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

and my classes

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; }
}
  • You have not indicated which line throws the exception. No doubt on `amount.paymentAmount.chargingInformation.amount = "1";` since `paymentAmount` is `null` and you cannot assign a value to a property of `null` –  Aug 30 '16 at 04:51
  • can you please tell me what the correct code example? – mostafa hakimi Aug 30 '16 at 04:56
  • Read the duplicate! You need to initialize `paymentAmount` - `amount.paymentAmount = new PaymentAmount();` before you assign a value (and ditto for `chargingInformation`) –  Aug 30 '16 at 04:57
  • please give me the correct block of code please... – mostafa hakimi Aug 30 '16 at 05:28
  • i did it. you are perfect ;-) – mostafa hakimi Aug 30 '16 at 06:13

1 Answers1

0

Your paymentAmount field on AmountTransaction is throwing a null reference because it hasn't been set to a new PaymentAmount instance.

Same with ChargingInformation on that class.

Sanoop Surendran
  • 3,484
  • 4
  • 28
  • 49
Donyo
  • 1