【问题标题】:How to deserialize an object and pass it to a response model如何反序列化对象并将其传递给响应模型
【发布时间】:2022-01-17 07:03:43
【问题描述】:

我有一个 json 字符串,我反序列化如下。

using (var streamReader = new StreamReader(httpResponsePayment.GetResponseStream()))
            {
                var data = streamReader.ReadToEnd();
                result = JsonConvert.DeserializeObject<TestResponse>(data);
            }

数据对象如下所示

"{\"responseCode\":2402,\"responseMessage\":\"hello\",\"amount\":0,\"acquirer\":{\"account\":{\"Number\":\"4587-54884-784848\"},\"Tag\":\"TF1234569775548494\"}}"

我将此对象传递给我的 TestResponse 类

public class TestResponse
    {
        
        public string responseCode { get; set; }
        public string responseMessage { get; set; }    
        public int amount { get; set; }
    }

我可以正确传递上述 3 个对象。我不知道如何将获取者对象传递给 TestResponse

          acquirer = new
                    {
                        account= new
                        {
                            Number="4587-54884-784848"
                        },
                        Tag= "TF1234569775548494"
                    }

我试着做这样的事情

public class TestResponse
        {
            
            public string responseCode { get; set; }
            public string responseMessage { get; set; }    
            public int amount { get; set; }
          List<Acquirers> acquirer =new List<Acquirers>();
        }
    public class Acquirers
        {
            public string Tag { get; set; }
        }

也试过了 公共类TestResponse {

            public string responseCode { get; set; }
            public string responseMessage { get; set; }    
            public int amount { get; set; }
            public string Number {get;set;} //returns null
            public string Tag {get;set;} // returns null
        }

有人可以指导我吗

【问题讨论】:

    标签: c# arrays asp.net json


    【解决方案1】:
    class Program
        {
            static void Main(string[] args)
            {
                var json = "{\"responseCode\":2402,\"responseMessage\":\"hello\",\"amount\":0,\"acquirer\":{\"account\":{\"Number\":\"4587-54884-784848\"},\"Tag\":\"TF1234569775548494\"}}";
                var result = JsonConvert.DeserializeObject<Root>(json);
            }
        }
        public class Account
        {
            public string Number { get; set; }
        }
    
        public class Acquirer
        {
            public Account account { get; set; }
            public string Tag { get; set; }
        }
    
        public class Root
        {
            public int responseCode { get; set; }
            public string responseMessage { get; set; }
            public int amount { get; set; }
            public Acquirer acquirer { get; set; }
        }
    

    您可以使用此链接 = https://json2csharp.com/ 用于转换模型

    【讨论】:

    • 天哪,谢谢!!
    猜你喜欢
    • 2021-05-11
    • 2017-06-23
    • 2021-11-08
    • 2020-02-23
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多