我正在尝试访问“success”属性以获取其值。现在,它正在命中“将对象引用设置为对象的实例。”如何获取字符串值?
{“success”:true,“next”:“/ locations”,“amount”:325,“keys”:3, “学分”:6185}
private static void postComplete(object sender, UploadStringCompletedEventArgs e)
{
object result = JsonConvert.DeserializeObject<object>(e.Result);
try{
PropertyInfo pi = result.GetType().GetProperty("success");
String success = (String)(pi.GetValue(result, null));
Console.Write(success);
}
catch (Exception f) {
Console.Write(f);
}
答案 0 :(得分:0)
您将其直接反序列化为object
.. object
没有名为success
的属性。
另一种方法是键入一个代表这个的类:
class ExampleClass {
public bool success { get; set; }
public string next { get; set; }
public int amount { get; set; }
public int keys { get; set; }
public int credits { get; set; }
}
然后这样称呼:
object result = JsonConvert.DeserializeObject<ExampleClass>(e.Result);
// ^^^^^^^^^^^^
// This
try{
PropertyInfo pi = result.GetType().GetProperty("success");
bool success = (bool)(pi.GetValue(result, null));
Console.Write(success); // True
}
catch (Exception f) {
Console.Write(f);
}
甚至更好..完全删除它:
ExampleClass example = JsonConvert.DeserializeObject<ExampleClass>(e.Result);
Console.WriteLine(example.success); // True