skip to Main Content

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?

3

Answers


  1. you can desirialize json to a dynamic variable and access to property which are in the object

    dynamic dynJson = JsonConvert.DeserializeObject(json);
    foreach (var item in dynJson)
    {
         // access dynamic property here
    }
    
    Login or Signup to reply.
  2. Try this

    var JsonObj = JObject.Parse(json);
    
    foreach(var keyvaluepair in JsonObj.Cast<KeyValuePair<string,JToken>>().ToList())
    {
        //keyvaluepair.Key
        //keyvaluepair.Value
    }
    
    Login or Signup to reply.
  3. 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!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search