簡體   English   中英

在C#中從json響應獲取對象屬性值

[英]getting object property value from json response in c#

我正在嘗試訪問“成功”屬性以獲取其值。 現在,它說“對象引用未設置為對象的實例。”該如何捕捉字符串值?

{“成功”:true,“下一個”:“ / 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);
        }

您正在將其反序列化為一個直截了當的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM