xMetalDetectorx
xMetalDetectorx

Reputation: 160

Parsing JSON error response in c#

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?

Upvotes: 1

Views: 2532

Answers (3)

Artak
Artak

Reputation: 2887

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!

Upvotes: 2

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38683

Try this

var JsonObj = JObject.Parse(json);

foreach(var keyvaluepair in JsonObj.Cast<KeyValuePair<string,JToken>>().ToList())
{
    //keyvaluepair.Key
    //keyvaluepair.Value
}

Upvotes: 1

programtreasures
programtreasures

Reputation: 4298

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
}

Upvotes: -1

Related Questions