First, you should consider naming your variables something easier to understand.
dJson2
is not a good way to name something, especially when you add more and more of these variables. Instead, give it a meaningful name like
nameComponents
so you know what it is in the future.
Second, for the issue you're seeing, it's primarily because you're not doing safety checks to ensure that there is available data. If you look at your JSON:
"state": "",
"street": [], <<--------
"type": "Permanent"
You can clearly see that the street is an empty array, therefore the length (once deserialized) will be 0. Now, let's look at your code:
dynamic dJson6 = dJson4["street"];
if (!string.IsNullOrWhiteSpace(dJson6[0].ToString()) ) <<--------
{
kv.Add("Address1", dJson6[0].ToString());
}}
What you've done here is get the value of the
"street"
property (which is that empty array with a length of 0) and then tried to access the first element in the array. But, there is no element at index 0 because the array is empty! So, this will throw an exception. You need to add a check to ensure that at least one value exists in the array before attempting to access it.
Finally, I don't know why you're using
JavaScriptSerializer
for handling JSON content. The best practise is to instead create classes which match the structure of your JSON, and then deserialize the JSON into these class objects:
How to serialize and deserialize JSON using C# - .NET | Microsoft Docs[
^]
Deserialize an Object[
^]