none
How to read Dictionary inside List inside nested dictionary RRS feed

  • Question

  • Hello,

    Here is the Json sample file:-

    {
        "contactDetails": [],
        "personDetails": [],
        "serviceDetails": [
            {
                "serviceTypeNm": "Tax Prep",
                "taxYearNo": "2019",
                "productTypeNm": [],
                "states": [
                    {


    Here is what I'm trying, but it is not able to read taxYearNo.

    This is the error: System.InvalidCastException : Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]'.

    public static IRestResponse response;
    
    var deseralize = new JsonDeserializer();
    var result = deseralize.Deserialize<IList<Dictionary<string, object>>>(response);
    
    foreach (Dictionary<string, object> temp in result)
                {
    
                    if (temp.ContainsKey("serviceDetails"))
                    {
                        var obj1 = temp.GetValueOrDefault("serviceDetails");
                        var taxyear = ((Dictionary<string, object>)obj1).GetValueOrDefault("taxYearNo");
                        Assert.Equal(2019, taxYearNo());
                    }
    
                }

    Any help or suggestions?

    Thanks,

    gk03


    Please do let us know your feedback. Thank You - KG, MCTS

    Sunday, March 22, 2020 2:09 AM

Answers

  • Try something like this too:

       dynamic a = obj1;

       object obj2 = a[0];

       var taxyear = ((Dictionary<string, object>)obj2).GetValueOrDefault("taxYearNo");

    or maybe even this:

       dynamic a = obj1;

       var taxyear = a[0]["taxYearNo"];

    • Edited by Viorel_MVP Sunday, March 22, 2020 9:00 AM
    • Marked as answer by gk1393 Monday, March 23, 2020 5:53 AM
    Sunday, March 22, 2020 8:58 AM

All replies

  • Create a class that represents the data structure and deserialize using json.net, see this example https://www.newtonsoft.com/json/help/html/DeserializeObject.htm

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Sunday, March 22, 2020 3:52 AM
    Moderator
  • Try something like this too:

       dynamic a = obj1;

       object obj2 = a[0];

       var taxyear = ((Dictionary<string, object>)obj2).GetValueOrDefault("taxYearNo");

    or maybe even this:

       dynamic a = obj1;

       var taxyear = a[0]["taxYearNo"];

    • Edited by Viorel_MVP Sunday, March 22, 2020 9:00 AM
    • Marked as answer by gk1393 Monday, March 23, 2020 5:53 AM
    Sunday, March 22, 2020 8:58 AM