Search code examples
c#jsonc#-3.0choetl

how to give exception handling for json string if an array found instead of object usinc C#


I am having a json text file as :

[
    { 
        "productId":"17213812",
        "returnPolicies": {
            "user":"Regular Guest"
        }
    },
    {
        "productId":"17813832",
        "returnPolicies":[]
    }
] 

and I am getting error for returnPolicies since it has different properties. But I want only returnpoliciesuser so If i use e.returnpolicies.user it is showing error for second array.. Anyone knows how to skip "returnPolicies":[] and search only e.returnpolicies.user("returnPolicies":{"user":"Regular Guest"}) ?


Solution

  • This is how you can do it.

    using (var jr = new ChoJSONReader("sample6.json")
        .WithField("ProductId", jsonPath: "$.productId")
        .WithField("User", jsonPath: "$.returnPolicies.user")
        )
    {
        foreach (var item in jr)
            Console.WriteLine(item.ProductId + " " + item.User);
    }