Finding difficulty in making a model in C#

Viewed 46

This question sounds very trivial but I couldn't find it on internet. Let's say I am getting response like following 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"
        }
    }
}

My problem is How do I make a Model in C# (So that I can deserialize this response)?

I tried this one -

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

I know the problem, Problem is "transaction_details" is not a List, It is object of object.

How do I model that, The number of Keys and name of the Keys are not known!!

Please help me!

and sorry if the question is too trivial.

1 Answers

Any time you are dealing with a JSON structure where the keys are not static (i.e. the key is a unique identifier, date/time, etc.) you will need to use a Dictionary. You will still have the benefit of using a strongly-typed value, and you can perform any validation operations on the key to handle different formats as necessary.

Related