Riley Varga
Riley Varga

Reputation: 720

How do I properly parse a JArray into a collection of strings

So I got this JArray stored in a variable of type object

public object Errors { get; }

which contains either this

Errors = {[
  {
    "name": [
      "Username "admin" has already been taken."
    ],
    "email": [
      "Email is not a valid email address."
    ]
  }
]}

Or it's going to contain this

Errors = {[
  "User not found."
]}

And I want to be able to extract the data like this.. email: "Email is not a valid email address."

And I'm not sure how to do it, and this is what I have so far

foreach (var error in (JArray)Errors)
{
    System.Console.WriteLine($"Type: {error.Type}");
}

How do I properly extract the errors so I get a collection containing the strings either like kvp or email: "Email is not a valid email address."

Upvotes: 0

Views: 206

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129787

How about something like this?

static List<string> ExtractErrors(JArray array)
{
    JToken item = array.FirstOrDefault();
    if (item.Type == JTokenType.Null)
    {
        return new List<string>();
    }
    if (item.Type == JTokenType.Object)
    {
        return item.Children<JProperty>()
                   .Select(jp => jp.Name + ": " + (string)jp.Value.FirstOrDefault())
                   .ToList();
    }
    return new List<string> { item.ToString() };
}

Here is a demo: https://dotnetfiddle.net/md1oyn

Upvotes: 1

Related Questions