Home > database >  How to deserialize an object and pass it to a response model
How to deserialize an object and pass it to a response model

Time:12-14

i have a json string that i deserialize as follows.

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

the data object looks as follows

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

i pass this object to my TestResponse class

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

i can pass the above 3 objects correctly. I dont know how to pass the acquirer object to the TestResponse

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

i tried doing something like this

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

also tried public class 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
        }

can someone please guide me

CodePudding user response:

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

you can using this link = https://json2csharp.com/ for convert model

  • Related