'Deserialized object type get value throw null reference
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.
Solution 1:[1]
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"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

