0

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!

1 Answer 1

2

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}");
    }                
}
Sign up to request clarification or add additional context in comments.

2 Comments

Parsing the array is unnecessary - can just be var jarray = objects["EmailAddresses"];
Thanks @stuartd for the finding. Have updated the post

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.