0

我有一个在 3 种不同情况下具有 1 个不同属性的 json 主体

我尝试了一些自定义方法,但都没有奏效。这是我的 jsonBody

var postParameters = new CredoPayRequest()
        {
            amount = amount,
            birthDate = Dob,
            currency = "GEL",
            currencyRate = 1,
            depositId = credoPayId,
            fee = 0,
            paymentDate = trx_date,
            personalNumber = personalNumber,
            terminalId = terminalId.ToString(),
            transactionId = invoiceID
        };

depositId 是以不同方式不同的东西,有时它会是 depositId 有时是 utilityId 和 loanId 。我能做些什么来改变这个价值而不是创造3个不同的身体?我的班级是

public class CredoPayRequest
{
    public string personalNumber { get; set; }
    public string transactionId { get; set; }
    public string terminalId { get; set; }
    public string paymentDate { get; set; }
    public string birthDate { get; set; }
    public string amount { get; set; }
    public int fee { get; set; }
    public string currency { get; set; }
    public int currencyRate { get; set; }
    public string accountId { get; set; }
    public string depositId { get; set; }
    public string utilityId { get; set; }

}

实用程序必须是这样的:

var postParameters = new CredoPayRequest()
    {
        amount = amount,
        birthDate = Dob,
        currency = "GEL",
        currencyRate = 1,
        utilityId = credoPayId,
        fee = 0,
        paymentDate = trx_date,
        personalNumber = personalNumber,
        terminalId = terminalId.ToString(),
        transactionId = invoiceID
    };

那么帐户必须是

var postParameters = new CredoPayRequest()
    {
        amount = amount,
        birthDate = Dob,
        currency = "GEL",
        currencyRate = 1,
        accountId = credoPayId,
        fee = 0,
        paymentDate = trx_date,
        personalNumber = personalNumber,
        terminalId = terminalId.ToString(),
        transactionId = invoiceID
    };
4

1 回答 1

1

有几个解决方案。最简单的一种是创建所有三个属性并分配适当的一个:

public class CredoPayRequest
{
    // properties shared between all requests
    // ...
    public string depositId { get; set; }
    public string utilityId { get; set; }
    public string loanId { get; set; }
}

var request = new CredoPayRequest
{
    // assign shared properties
    // ...
    utilityId = "Foo"
};

但默认情况下,这将序列化所有三个属性,其中两个有一个null值,并允许开发人员意外分配一个或多个,这可能是一个错误。

或者,您可以为每个请求创建一个类,从基本请求继承:

public abstract class CredoPayRequest
{
    // properties shared between all requests
}

public class DepositRequest : CredoPayRequest
{   
    public string depositId { get; set; }
}

public class UtilityRequest : CredoPayRequest
{   
    public string utilityId { get; set; }
}

public class LoanRequest : CredoPayRequest
{   
    public string loanId { get; set; }
}

var request = new DepositRequest
{
    // assign shared properties
    // ...
    depositId = "Foo"
};

这可以防止空属性的无用序列化(可以通过各种方式避免,例如NewtonSoft add JSONIGNORE at runTime),但更重要的是,强制开发人员显式实例化他们想要发出的请求。没有犯错的余地。

于 2019-04-11T11:29:57.880 回答