Scott
Scott

Reputation: 63

"Cannot access child value on Newtonsoft.Json.Linq.JValue."

Sorry if this is a basic one, I'm fairly new to this.

I have a JObject jObj with JSON data that may or may not have a child object.

Scenario 1

  },
  "feedback": {
    "rating": false,
    "comment": "test"
  },

Scenario 2

  },
  "feedback": null,

What I am trying to do is handle both scenarios, initially I thought if a child object didn't exist I could evaluate with null but it doesn't appear to be that simple.

var jObj = (JObject)JsonConvert.DeserializeObject(JSON, new JsonSerializerSettings() { DateParseHandling = DateParseHandling.None });

string rating = (string)jObj["feedback"]["rating"];
string rating_comment = (string)jObj["feedback"]["rating_comment"];

Scenario 1 works a treat but Scenario 2 throws the following exception.

"Cannot access child value on Newtonsoft.Json.Linq.JValue."

I then tried a different approach in an attempt to evaluate if "feedback" had an object before I referenced the feedback keys.

JObject jObjFeedback = (JObject)jObj.GetValue("feedback");
bool containsFeedback = jObjFeedback.ContainsKey("rating");

if (containsFeedback)
{
    rating = (string)jObj["feedback"]["rating"];
    rating_comment = (string)jObj["feedback"]["rating_comment"];
}
else
{
    log.Info("No feedback rating found");
}

Again this worked fine for Scenario 1 as the feedback object exists, but when it doesn't I get the following exception.

"Unable to cast object of type 'Newtonsoft.Json.Linq.JValue' to type 'Newtonsoft.Json.Linq.JObject'"

I'm sure there must be a simple way to handle the two scenarios, unfortunately I can't seem to find it.

Any help is much appreciated.

Upvotes: 6

Views: 18628

Answers (1)

Akshay G
Akshay G

Reputation: 2280

Use the HasValues Property to check if feedback has Child Object

var jObj = (JObject)JsonConvert.DeserializeObject(JSON, new JsonSerializerSettings() { DateParseHandling = DateParseHandling.None });

if(jObj.GetValue("feedback").HasValues)
{
    var rating = (string)jObj["feedback"]["rating"];
    var rating_comment = (string)jObj["feedback"]["rating_comment"];
}          
else
{
    log.Info("No feedback rating found");
}

Upvotes: 7

Related Questions