繁体   English   中英

反序列化 object type get value throw null reference

[英]Deserialized object type get value throw null reference

我有一个来自 ajax 的 json 响应,我正在尝试将其反序列化为 object 类型(不是定义的 model 类)并访问其属性值。 反序列化器工作正常但是当尝试获取值时我得到 null 参考错误。

// 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();

我尝试了测试数据

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

它工作正常。 我不明白为什么反序列化器启动的 object 不是 null 在获取属性值时抛出错误。

对象值

JsonConvert.DeserializeObject<object>返回一个JObject实例 class 没有名为tankName的属性,因此tankJsonObj.GetType().GetProperty("tankName")返回null

当您使用匿名类型进行测试时,该类型确实有一个名为tankName的属性。

您不需要反射来从JObject中提取值:

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

第一个GetValue()参数需要是tankJsonObj ,因为将从 object 中读取值。

更改代码:

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

工作演示: https://do.netfiddle.net/tOtRUf


但是,当反序列化为object时,只有object支持的属性才会被反序列化,并且没有......没有。 因此,JSON 中的所有属性都将被忽略。

一个简单的解决方法是改用JObject作为目标类型(在Newtonsoft.Json.Linq命名空间中)。 这有点像键和值的字典,并且将接受任何属性。 生成的代码非常简单,甚至不需要反射:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM