【问题标题】:Finding difficulty in making a model in C#在 C# 中制作模型时遇到困难
【发布时间】:2021-11-20 20:27:51
【问题描述】:

这个问题听起来很琐碎,但我在互联网上找不到。假设我收到了类似 json 的响应

{
    "status": 1,
    "msg": "1 out of 2 Transactions Fetched Successfully",
    "transaction_details": {
        "f9605b13-c300-4d11-b": {
            "mihpayid": "14019310624",
            "txnid": "f9605b13-c300-4d11-b",
            "mode": "UPI",
            "status": "success",
            "App_Name": "PhonePe"
        },
        "546576": {
            "mihpayid": "Not Found",
            "status": "Not Found"
        }
    }
}

我的问题是如何在 C# 中制作模型(以便我可以反序列化此响应)?

我试过这个 -

public class TransactionDetails
{
    [JsonProperty("txnid")]
    public string TransactionId;

    [JsonProperty("status")]
    public string Status { get; set; }

    [JsonProperty("mode")]
    public string Mode { get; set; }

    [JsonProperty("mihpayid")]
    public string MiPayId { get; set; }

    [JsonProperty("amt")]
    public string amount { get; set; }

    [JsonProperty("App_name")]
    public string AppName { get; set; }

}
public class ResponseBody
{
    [JsonProperty("status")]
    public string Status { get; set; }

    [JsonProperty("msg")]
    public string Message { get; set; }

    [JsonProperty("transaction_details")]
    public List<TransactionDetails> Transactions { get; set; }
}

我知道问题所在,问题是“transaction_details”不是列表,它是对象的对象。

我如何建模,钥匙的数量和钥匙的名称是未知的!

请帮帮我!

如果问题太琐碎,请见谅。

【问题讨论】:

  • 尝试 Dictionary 而不是列表。让我知道这是否有帮助。

标签: c# asp.net json


【解决方案1】:

任何时候您在处理键不是静态的 JSON 结构(即键是唯一标识符、日期/时间等)时,您都需要使用字典。您仍将受益于使用强类型值,并且您可以对键执行任何验证操作以根据需要处理不同的格式。

【讨论】:

    猜你喜欢
    • 2017-05-20
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    • 2016-08-11
    • 1970-01-01
    相关资源
    最近更新 更多