Shoy
Shoy

Reputation: 21

Parse Array inside of an JSON Object with C#

I'm trying to parse an array inside of a json Object but it's not working, here is the code:

public void JsonParserPersonal(string file)
        {
            string fullname;
            string email;

            var json = System.IO.File.ReadAllText(file);
            var objects = JObject.Parse(json);
            var arrays = JArray.FromObject(json);

            fullname = (string)objects["NameComponents"]["FullName"];
            email = (string)arrays["EmailAddresses"]["ItemValue"];
            SearchReplacePersonal(fullname, email);
        }

Here is the JSON data:

{
    "NameComponents": {
        "FullName": "XXX"
    },
    "EmailAddresses": [
        {
            "IsPersonal": true,
            "IsBusiness": false,
            "FieldName": "Email1Address",
            "DisplayTitle": "Email",
            "ItemValue": "[email protected]"
        }
    ]
}

All I want is to get the "ItemValue" inside of "EmailAddresses". When I run this code, this is the error I get:

System.ArgumentException: 'Object serialized to String. JArray instance expected.'

I'm using Visual Studio 2019.

Thanks!

Upvotes: 0

Views: 893

Answers (1)

Krishna Varma
Krishna Varma

Reputation: 4250

When accessing JArray, you should specify the index

var objects = JObject.Parse(json);
var jarray = objects["EmailAddresses"];

Console.WriteLine((string)objects["NameComponents"]["FullName"]);
Console.WriteLine((string)jarray[0]["ItemValue"]);

Or iterate JArray

foreach(var item in jarray)
{
    foreach(JProperty property in item.Children())
    {
        Console.WriteLine($"{property.Name} - {property.Value}");
    }                
}

Upvotes: 2

Related Questions