Vinod Saini
Vinod Saini

Reputation: 145

Read JSON Dynamically created headers in asp.net c#

How to read dynamically generated headers values in C# class from JSON string

In below JSON OrderVINOD_20190805224043295 is dynamic - can be X can b Y !!

Sample JSON

{
      "status": 1,
      "msg": "1 out of 1 Transactions Fetched Successfully",
      "transaction_details": {
          "OrderVINOD_20190805224043295": {
              "mihpayid": "403993715519706476",
              "request_id": "",
              "bank_ref_num": "313124",
          }
      }
}

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); 
var serializer = new JavaScriptSerializer();
dynamic jsons = serializer.Deserialize<MyClass>(responseString);

Upvotes: 2

Views: 1408

Answers (2)

Brian Rogers
Brian Rogers

Reputation: 129777

You can handle the dynamic key using a Dictionary<string, T> where T is a class to hold the transaction details. Define your classes like this:

public class MyClass
{
    public int status { get; set; }
    public string msg { get; set; }
    public Dictionary<string, Transaction> transaction_details { get; set; }
}

public class Transaction
{
    public string mihpayid { get; set; }
    public string request_id { get; set; }
    public string bank_ref_num { get; set; }
}

Then you can deserialize as you were before (you don't need dynamic though):

var serializer = new JavaScriptSerializer();
var myClass = serializer.Deserialize<MyClass>(responseString);

If you have not used a dictionary before, here is how you would get the data out of it:

foreach (var kvp in myClass.transaction_details)
{
    Console.WriteLine("transaction ID: " + kvp.Key);
    Console.WriteLine("mihpay ID: " + kvp.Value.mihpayid);
    Console.WriteLine("request ID: " + kvp.Value.request_id);
    Console.WriteLine("bank ref num: " + kvp.Value.bank_ref_num);
}

Upvotes: 0

AlwaysLearning
AlwaysLearning

Reputation: 8819

You can decorate your transaction_details class with a custom JsonConverter type declaration, such as the following...

// Install-Package Newtonsoft.Json
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Reflection;

namespace Read_JSON_Dynamically_created_headers
{
    public class VinodJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType.IsClass;
        }

        public override bool CanWrite
        {
            get { return false; }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            object instance = objectType.GetConstructor(Type.EmptyTypes).Invoke(null);
            PropertyInfo[] props = objectType.GetProperties();

            JObject jo = JObject.Load(reader);
            foreach (JProperty jp in jo.Properties())
            {
                var headValue = jp.Name;
                string tailValue = null;
                if (jp.Name.StartsWith("OrderVINOD_"))
                {
                    headValue = "OrderVINOD";
                    tailValue = jp.Name.Substring(11);
                }

                PropertyInfo headProperty = props.FirstOrDefault(pi =>
                    pi.CanWrite && string.Equals(pi.Name, headValue, StringComparison.OrdinalIgnoreCase));
                if (headProperty != null)
                    headProperty.SetValue(instance, jp.Value.ToObject(headProperty.PropertyType, serializer));

                if (tailValue != null)
                {
                    PropertyInfo trailProperty = props.FirstOrDefault(pi =>
                        pi.CanWrite && string.Equals(pi.Name, "restOfVINOD", StringComparison.OrdinalIgnoreCase));
                    if (trailProperty != null)
                        trailProperty.SetValue(instance, tailValue);
                }
            }
            return instance;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }

    public class MyClass
    {
        public string status { get; set; }
        public string msg { get; set; }
        public transaction_details transaction_details { get; set; }
    }

    [JsonConverter(typeof(VinodJsonConverter))]
    public class transaction_details
    {
        public ABC OrderVINOD { get; set; }
        public string restOfVINOD { get; set; }
    }

    public class ABC
    {
        public string bank_ref_num { get; set; }
        public string mihpayid { get; set; }
        public string request_id { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var json = @"{
""status"": 1,
""msg"": ""1 out of 1 Transactions Fetched Successfully"",
""transaction_details"": {
  ""OrderVINOD_20190805224043295"": {
    ""mihpayid"": ""403993715519706476"",
    ""request_id"": """",
    ""bank_ref_num"": ""313124"",
    }
  }
}";

            var obj = JsonConvert.DeserializeObject<MyClass>(json);
        }
    }
}

Upvotes: 2

Related Questions