0

I am using an API for car HP and PCP details. When API returns the response object it has some dynamic object and objects names depending upon the parameters given during JSON call input parameters. Please tell me how can I convert / deserialize this response object into C# object. I tried JSON convert to C# classes but didn't get required results. Given below in API response object. I need to parse this result object into C# object so i can use it for displaying required values on front end.

JSON Response / Result Object

{
    "success": true,
    "data": {
        "hp": {
            "58995": {
                "48": {
                    "40": {
                        "9000": [
                            {
                                "balance": 58955,
                                "first": 1403.62,
                                "regular": 1403.62,
                                "final": 1413.62,
                                "total": 67423.76,
                                "charges": 8428.76,
                                "apr": 6.92,
                                "apr_nofees": 6.91,
                                "term": 48,
                                "flat": 3.57,
                                "fee_front": "0.00",
                                "fee_back": "10.00",
                                "fee_spread": 0,
                                "ref": "1000.00",
                                "ho": 0,
                                "ho_a": 0,
                                "sb": 0,
                                "id": "12",
                                "product_name": "HP/ML No Fees",
                                "excess_mileage": false
                            }
                        ]
                    }
                }
            }
        },
        "pcp": {
            "58995": {
                "48": {
                    "40": {
                        "9000": [
                            {
                                "balance": 58955,
                                "first": 1251.04,
                                "regular": 1251.04,
                                "final": 8386,
                                "total": 68475.92,
                                "charges": 9480.92,
                                "apr": 6.89,
                                "apr_nofees": 6.89,
                                "rv": 8385,
                                "term": 48,
                                "flat": 3.56,
                                "rv_interest": 1084.68,
                                "charges_ex_rv": 8396.24,
                                "fee_front": "0.00",
                                "fee_back": "1.00",
                                "fee_spread": 0,
                                "ref": 0,
                                "ho": 0,
                                "ho_a": 0,
                                "sb": 0,
                                "id": "25",
                                "product_name": "BNP PCP",
                                "excess_mileage": "7p"
                            }
                        ]
                    }
                }
            }
        },
        "count": 2,
        "taken": 443
    }
}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Mr. Waqas
  • 35
  • 2
  • 10
  • In JavaScript and JSON objects are actually dictionaries. You can deserialize JSON parts into `Dictionary` in C# as well. There are several duplicate questions that ask the same thing. The answers show that "objects" with arbitrary keys can be deserialized to `Dictionary` types – Panagiotis Kanavos Jun 23 '22 at 11:09
  • how to read json as .net objects deserialize - https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-6-0#how-to-read-json-as-net-objects-deserialize – Diego D Jun 23 '22 at 11:10
  • Just how dynamic is this dynamic structure? It looks like at least 4 levels of dictionaries will be needed. Is `hp` dynamic as well? Is the innermost object well defined? With so many levels it may be better to deserialize to a JObject and try to retrieve items element by element. A `Dictionary>>>>>>>>>>>>>>>>>>` isn't fun – Panagiotis Kanavos Jun 23 '22 at 11:12
  • Does this answer your question? https://stackoverflow.com/a/3806407/1221208 – Diego D Jun 23 '22 at 11:12
  • i used online json to c# classes converter but the classes it made didn't meet the requirement because the given above response object has some dynamic classes like "58995", "48", "40" and "9000". Actually these are the parameters values which is used while sending call to API. these values can be different in each call. The online convert created the classes with these names which is not required. can you suggest any method to handle these dynamic classes at the time of parsing response object in c# object – Mr. Waqas Jun 23 '22 at 11:13
  • @DiegoDeVita that's an unrelated question. Not only does it not answer this problem, it even uses the obsolete JavaScriptSerializer class that was replaced by JSON.NET almost 10 years ago – Panagiotis Kanavos Jun 23 '22 at 11:14
  • @PanagiotisKanavos... i used online json to c# classes converter but the classes it made didn't meet the requirement because the given above response object has some dynamic classes like "58995", "48", "40" and "9000". Actually these are the parameters values which is used while sending call to API. these values can be different in each call. The online convert created the classes with these names which is not required. can you suggest any method to handle these dynamic classes at the time of parsing response object in c# object – Mr. Waqas Jun 23 '22 at 11:15
  • @Mr.Waqas these aren't dynamic classes, they're dictionaries. JSON has no classes, it has dictionaries or arrays. Serializers map this structure to objects and arrays of objects. In Javascript objects *are* dictionaries, so the mapping is straightforward. In C# you'll have to use dictionaries for the unstructured parts – Panagiotis Kanavos Jun 23 '22 at 11:15
  • 1
    @PanagiotisKanavos yes that comment was added automatically when I flagged the question.. by the way after retracting my flag I edited my comment to include an answer to SO that did just that (deserialize json dynamic object in c#) with few lines. There are plenty of questions like this on SO – Diego D Jun 23 '22 at 11:16
  • @PanagiotisKanavos. thank you. can you please quote an example or sample code according to my given response object. this would be very grateful if you can – Mr. Waqas Jun 23 '22 at 11:19

1 Answers1

2

try this

    var jsonParsed = JObject.Parse(json);
    var count = (int)jsonParsed["data"]["count"];
    var taken = (int)jsonParsed["data"]["taken"];

    ((JObject)jsonParsed["data"]).Descendants()
   .OfType<JProperty>()
   .Where(attr => attr.Name == "count" || attr.Name == "taken")
   .ToList()
   .ForEach(attr => attr.Remove());

    Data data = jsonParsed.ToObject<Data>();
    data.count = count;
    data.taken = taken;

classes

public class Data
{
    public bool success { get; set; }
    public Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, Dictionary<string, Product[]>>>>> data { get; set; }
    public int count { get; set; }
    public int taken { get; set; }

public class Product
{
    public int balance { get; set; }
    public double first { get; set; }
    public double regular { get; set; }
    public double final { get; set; }
    public double total { get; set; }
    public double charges { get; set; }
    public double apr { get; set; }
    public double apr_nofees { get; set; }
    public int term { get; set; }
    public double flat { get; set; }
    public string fee_front { get; set; }
    public string fee_back { get; set; }
    public int fee_spread { get; set; }
    [JsonProperty("ref")]
    public string refer { get; set; }
    public int ho { get; set; }
    public int ho_a { get; set; }
    public int sb { get; set; }
    public string id { get; set; }
    public string product_name { get; set; }
    public object excess_mileage { get; set; }
}
Serge
  • 40,935
  • 4
  • 18
  • 45