Search code examples
c#jsonjson.net

Dynamic Json string access a value



    {
  "ErrorNumber": 10,
  "Type": "ValidationException",
  "Message": "A validation exception occurred",
  "Elements": [
    {
      "ContactID": "00000000-0000-0000-0000-000000000000",
      "Name": "Test AB",
      "EmailAddress": "[email protected]",
      "Addresses": [
        {
          "AddressType": "POBOX",
          "ValidationErrors": []
        }
      ],
      "Phones": [],
      "ContactGroups": [],
      "IsCustomer": true,
      "ContactPersons": [],
      "HasValidationErrors": true,
      "ValidationErrors": [
        {
          "Message": "The contact name Test AB is already assigned to another contact. The contact name must be unique across all active contacts."
        }
      ]
    }
  ]
}

Tried to deserialize the object.

var x = ((Xero.NetStandard.OAuth2.Client.ApiException)ex.InnerException).ErrorContent;
                dynamic parsedObject = JsonConvert.DeserializeObject(x);

I have a dynamic Json string which is coming from Xero API exception. How can I access the value "ValidationErrors" and the Message?


Solution

  • Using json.net you can just navigate the graph with string indexers

    var errors = JObject.Parse(json)["Elements"][0]["ValidationErrors"];
    
    foreach (var error in errors)
       Console.WriteLine(error["Message"]);
    

    Output

    The contact name Test AB is already assigned to another contact. The contact name must be unique across all active contacts.