Home > database >  Deserialized object type get value throw null reference
Deserialized object type get value throw null reference

Time:02-12

i have a json response from ajax and i am trying to deserialize it as object type(not a defined model class) and access its properties value. deserializer works fine but when try to get the value i get the null reference error.

// on break point i can clearly see the object properties and values and its not null
var tankJsonObj = JsonConvert.DeserializeObject<object>(tankJson);

//here from GetValue i get the null refernce error
var test = tankJsonObj.GetType().GetProperty("tankName").GetValue(tankJsonObj, null).ToString();

i tried the test data

var tankJsonObj = new { tankName = "xx" };
var test = tankJsonObj.GetType().GetProperty("tankName").GetValue(tankJsonObj, null).ToString();

and it works fine. i cant understand why the object that initiated by deserializer which is not null throwing the error on getting the property value.

object value

CodePudding user response:

JsonConvert.DeserializeObject<object> returns a JObject instance. That class does not have a property called tankName, so tankJsonObj.GetType().GetProperty("tankName") returns null.

When you test using an anonymous type, that type does have a property called tankName.

You don't need reflection to extract values from a JObject:

JObject tankJsonObj = JsonConvert.DeserializeObject<JObject>(tankJson);
string tankName = tankJsonObj["tankName"]?.ToString();

CodePudding user response:

The first GetValue() parameter needs to be tankJsonObj because from that object the values will be read.

Changed code:

var tankJsonObj = new { tankName = "xx" };
var test = tankJsonObj.GetType().GetProperty("tankName").GetValue(tankJsonObj, null).ToString();
Console.WriteLine(test); // "xx"

Working demo: https://dotnetfiddle.net/tOtRUf


However when deserializing to object, only properties that object supports will be deserialized, and there are... none! As a result all properties inside the JSON will be ignored.

A simple workaround is to instead use JObject as the target type (in the Newtonsoft.Json.Linq namespace). This behaves somewhat like a Dictionary of keys and values, and will accept any property. The resulting code is very simple, it doesn't even need reflection:

var tankJsonObj = JsonConvert.DeserializeObject<JObject>("{ tankName: \"xx\" }");
var test = tankJsonObj.GetValue("tankName")?.ToString();
Console.WriteLine(test); // "xx"
  • Related