0

我正在尝试访问“成功”属性以获取其值。现在,它正在说“对象引用未设置为对象的实例”。我如何获取字符串值?

{ "success": true, "next": "/locations", "amount": 325, "keys": 3, "credits": 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);
        }
4

1 回答 1

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
于 2013-02-13T04:36:55.277 回答