Doing a simple JObject.parse(inJson) from Newtonsoft.json gives me the error Unable to cast object of type 'Newtonsoft.Json.Linq.JValue' to type 'Newtonsoft.Json.Linq.JObject

I found the problem and fixed it. The problem was that I had assumed if inside an array if the value is not a string then it is an object:-

else if (property.Value.Type == JTokenType.Array)
{
JArray array = (JArray) property.Value;

	foreach (JToken innerProperty in array.Children()) {
		if (innerProperty.Type == JTokenType.String) {
			innerProperty.ToString();
			JValue value = (JValue) innerProperty;

			if (value.Value.ToString().Length > 50)
			{
				value.Value = value.Value.ToString().Substring(0, 50);
			}
		} else { 
			JObject obj = (JObject)innerProperty;

			foreach (JProperty p in obj.Properties())
			{
				processJProperty(p);
			}
		}
	}

I changed it, and applied a check if type Object and not do anything if it is not an object:-
else if (property.Value.Type == JTokenType.Array)
{
JArray array = (JArray) property.Value;

foreach (JToken innerProperty in array.Children()) {
	if (innerProperty.Type == JTokenType.String) {
		innerProperty.ToString();
		JValue value = (JValue) innerProperty;

		if (value.Value.ToString().Length > 50)
		{
			value.Value = value.Value.ToString().Substring(0, 50);
		}
	} else {
		if (innerProperty.Type == JTokenType.Object)
		{
			JObject obj = (JObject)innerProperty;

			foreach (JProperty p in obj.Properties())
			{
				processJProperty(p);
			}
		}
		else
		{

		}
	}
}

}

Thank you guys for your support.

1 Like