Click here to Skip to main content
15,881,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
"patients": [
    {
      "addresses": [
        {
          "city": "",
          "country": "United States of America",
          "county": "",
          "district": null,
          "email": [],
          "houseNumber": null,
          "phoneNumbers": [],
          "postalCode": "",
          "state": "",
          "street": [],
          "type": "Permanent"
        }]}]



this one is json format I am using and the code is like below to get the data,I am getting exceptions at the last line so if there is no data in JSON and it's in array format how do not get an exception, is there any typecasting of an array or something.. plz improve my code there 



I am getting error here
if (!string.IsNullOrWhiteSpace(dJson6[0].ToString())  )
                   {
                       kv.Add("Address1", dJson6[0].ToString());
                   }}


What I have tried:

kv = new Dictionary<string, string>();
                  listKV = new List<Dictionary<string, string>>();



               FileInfo FI = new FileInfo(@"D:\Suraj\navicent\patientresponse500102785.json");
               FileStream FS = FI.Open(FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
               StreamReader sJson = new StreamReader(FS);

               string fileContent = sJson.ReadToEnd();
               //dynamic Valuejson = JsonConvert.DeserializeObject<dynamic>(fileContent);
               dynamic Valuejson = new JavaScriptSerializer().Deserialize<dynamic>(fileContent);
               dynamic dJson = Valuejson["patients"][0];
                   Log.Write("Value in djson  " + dJson.ToString());
                   dynamic dJson2 = dJson["nameComponents"];
                   Log.Write("Value in dJson2 is  " + dJson2.ToString());
                   if (!string.IsNullOrWhiteSpace(dJson2["lastName"].ToString()))
                   {
                       kv.Add("Last Name", dJson2["lastName"].ToString());
                       Log.Write("Value in kv  " + kv.ToString());
                   }
                     dynamic dJson6 = dJson4["street"];

                   if (!string.IsNullOrWhiteSpace(dJson6[0].ToString())  )
                   {
                       kv.Add("Address1", dJson6[0].ToString());
                   }}
Posted
Updated 29-Jun-22 3:37am
v2

1 solution

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[^]
 
Share this answer
 
Comments
Suraj Ingle 29-Jun-22 10:11am    
!string.IsNullOrWhiteSpace(dJson6[0].ToString()) I put [0] here for another JSON file which include street value. So that is my question what should I do so exception not come not removing [0]
Chris Copeland 29-Jun-22 10:14am    
As I said, you need to check that the dJson6 variable has values in it. I'm not familiar with using JavaScriptSerializer (please see the extra comments in my solution, you shouldn't be using this class but instead using either the built-in JsonSerializer class or using the Newtonsoft.Json package) so I can't tell you how to do that, but if I was to guess I would think there'd be a Length property on the value. If there is, you need to first check if the length is greater than zero, and then check whether the first element is null or whitespace.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900