在反序列化时动态获取对象类型

时间:2018-04-19 17:12:22

标签: c# dynamic json.net

在我申请的一个单元中:

// response is a string. After this line executes, obj is dynamic as expected
var obj = JsonConvert.DeserializeObject<dynamic>(response);
if (obj.Foo == "this works fine because obj is dynamic") {
   // Do whatever
}

在我的申请中的另一个单位:

// Again, response is a string. This time, obj ends up being an object, NOT dynamic
var obj = JsonConvert.DeserializeObject<dynamic>(response);
obj.Foo; // Fails because obj is an object
((dynamic)obj).Foo; // Works once I have type casted

// Every single method here returns an object and not dynamic as expected
dynamic obj2 = JsonConvert.DeserializeObject<dynamic>(response);
var obj3 = (dynamic)JsonConvert.DeserializeObject<dynamic>(response);
dynamic obj4 = (dynamic)JsonConvert.DeserializeObject<dynamic>(response);
dynamic obj5;
obj5 = (dynamic)JsonConvert.DeserializeObject<dynamic>(response);

我不介意对此进行拼写。但我认为不应该这样做。并且类似于这种感觉就像一个黑客。我宁愿理解为什么在某些情况下这种行为会有所不同。

屏幕截图,以防我看不到的东西:

enter image description here

enter image description here

0 个答案:

没有答案