locked
Dealing with missing JSON data (JObject.Parse) RRS feed

  • Question

  • User562699594 posted

    I have the following dataset:

    {
      "firstname": {
        "value": "Bill"
      },
      "lastmodifieddate": {
        "value": "1577625867421"
      },
      "lastname": {
        "value": "Mores"
      }
    }
    {
      "lastmodifieddate": {
        "value": "1577831623901"
      }
    }
    {
      "firstname": {
        "value": "Kelly"
      },
      "lastmodifieddate": {
        "value": "1577625867421"
      },
      "lastname": {
        "value": "Jones"
      }
    }

    And I'm looping through like so

     foreach (var item in jcontacts.ToList())
                        {
                                Debug.WriteLine(item["properties"]["firstname"]["value"]);
                        }

    It errors on the second item because firstname isn't there, just the modified date. "System.NullReferenceException: 'Object reference not set to an instance of an object.'"  It finds the first first name without an issue.  Can someone help me avoid this?

    Thursday, January 2, 2020 11:10 PM

All replies

  • User-474980206 posted

     your json string is invalid, and not sure why you  have .ToList(), but to handle missing properties it just:

     Debug.WriteLine(item["properties"]?["firstname"]?["value"]);

    Thursday, January 2, 2020 11:57 PM
  • User711641945 posted

    Hi id2ma,

    Your json file is not valid.Could you share a simple demo that how did you get the json and what is your `jcontacts.ToList()`? It could help us reproduce your issue.

    Correct json file should be something like below:

    {
      "properties": [
        {
          "firstname": {
            "value": "Bill"
          },
          "lastmodifieddate": {
            "value": "1577625867421"
          },
          "lastname": {
            "value": "Mores"
          }
        },
        {
          "lastmodifieddate": {
            "value": "1577831623901"
          }
        },
        {
          "firstname": {
            "value": "Kelly"
          },
          "lastmodifieddate": {
            "value": "1577625867421"
          },
          "lastname": {
            "value": "Jones"
          }
        }
      ]
    }
    

    Best Regards,

    Rena

    Friday, January 3, 2020 8:46 AM