【问题标题】:How convert Json string to key value pair in c#?如何在 C# 中将 Json 字符串转换为键值对?
【发布时间】:2015-03-23 07:21:38
【问题描述】:
   {
      "transactionId" : XXXXX,
      "uri" : "https://XXX.XXXXXXXX.XXXX/XXX/XXX",
      "terminalId" : 1,
      "action" : "CHARGE",
      "amountBase" : "3.00",
      "amountTotal" : "3.00",
      "status" : "CAPTURE",
      "created" : "2015-01-24T07:24:10Z",
      "lastModified" : "2015-01-24T07:24:10Z",
      "response" : 
       {
           "approved" : true,
           "code" : "00",
           "message" : "Approved",
           "processor" : 
            {
               "authorized" : true,
               "approvalCode" : "XXXX",
               "avs" : 
                     {
                         "status" : "NOT_REQUESTED"
                     },
            }
  },
  "settlement" : 
   {
        "settled" : false
   },
  "vault" : 
   {
        "type" : "CARD",
        "accountType" : "VISA",
        "lastFour" : "1111"
  }

}

【问题讨论】:

  • 这个 JSON 不适合“键值对”,即字典

标签: c# .net regex json parsing


【解决方案1】:

我看到这有很多反对票,但实际上没有人提供任何建议。上面的 json 不适合字典,但应该反序列化为对象。

响应、结算和保险库都有自己的属性,因此应该是自己的对象。

查看 Json.net 以获得将 json 转换为 c# 对象的好方法。如果您对如何在 C# 中表示此对象感到困惑,那么您需要阅读一本关于编程的好书,特别是一本涵盖面向对象编程的书。

Stack 是解决这些问题的绝佳资源,但您需要先尝试证明您已经完成了自己的研究,否则其他人只会记下您的问题。

【讨论】:

    【解决方案2】:

    您是否收到包含 JSON 的 POST ?

    您可以使用类似这样的方法,创建 Request 类的实例并将 JSON obj 分配给该实例。您应该能够通过请求实例访问参数。

    基本结构看起来像这样:

    public class Request
    {
        public Int64 transactionId { get; set; }
        public string uri { get; set; }
        public int terminalId { get; set; }
        public string action { get; set; }
        public string amountBase { get; set; }
        public int amountTotal { get; set; }
        public string status { get; set; }
        public DateTime created { get; set; }
        public DateTime lastModified { get; set; }
        public Response response { get; set; }
        public Settlement settlement { get; set; }
        public Vault vault { get; set; }
    }
    public class Response
    {
        public bool approved { get; set; }
        public int code { get; set; }
        public string message { get; set; }
        public Processor processor { get; set; }
    }
    public class Processor
    {
        public bool authorized { get; set; }
        public string approvedCode { get; set; }
        public AVS avs { get; set; }
    }
    public class AVS
    {
        public string status { get; set; }
    }
    public class Settlement
    {
        public bool settled { get; set; }
    }
    public class Vault
    {
        public string type { get; set; }
        public string accountType { get; set; }
        public string lastFour { get; set; }
    }
    

    希望对你有帮助!!

    【讨论】:

    • 仅供参考,您可以通过将 json 转储到 json2csharp.com 来自动生成上述内容。
    猜你喜欢
    • 2017-08-03
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多