How to fix "object reference not set to an instance of an object"

时间:2016-08-30 04:41:05

标签: json asp.net-mvc-5

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

1 个答案:

答案 0 :(得分:0)

paymentAmount上的AmountTransaction字段正在引发null引用,因为它尚未设置为新的PaymentAmount实例。

与该班级的ChargingInformation相同。