Ad

Parsing JSON Error Response In C#

- 1 answer

I'm trying to figure out a way to parse JSON error messages in C#. I can receive a response that looks like this:

{
  "errors": {
    "title": ["can't be blank"]
  }
}

or

{
    "errors": {
        "inventory_policy": ["is not included in the list"]
    }
}

or maybe I will receive more than one error in the response.

How would I be able to parse that kind of dynamic response in C#? The key is different for each error message. Could I deserialize it to an object that just has a Dictionary of strings called errors?

Ad

Answer

JObject class has an internal dictionary of those properties. Instances of it can be enumerated, and each of the child object can be accessed. Here is a sample code:

string input = "{  \"errors\": {    \"title\": [\"can't be blank\"]  }}";
JObject json = JObject.Parse(input);

foreach (var item in json)
{
    Console.WriteLine($"{item.Key} _ {item.Value}");
}

The JObject class is defined in the Newtonsoft.Json package, and to reference it from your project you'll need to add the following package reference in your csproj file (or just do that yourself using Nuget Package Manager):

  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
  </ItemGroup>

Hope this will help!

Ad
source: stackoverflow.com
Ad