简体   繁体   English

在C#中从json响应获取对象属性值

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

I am trying to access the "success" property to get its value. 我正在尝试访问“成功”属性以获取其值。 Right now, it is hitting catch saying "Object reference not set to an instance of an object. " How do I get the string value? 现在,它说“对象引用未设置为对象的实例。”该如何捕捉字符串值?

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

You're deserializing it as a straight up object .. object doesn't have a property named success . 您正在将其反序列化为一个直截了当的object .. object没有名为success的属性。

The alternative is to type a class that represents this: 替代方法是键入一个表示该类的类:

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; }
}

Then call it like this: 然后这样称呼它:

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);
    }

Or even better.. remove that altogether: 甚至更好..完全删除:

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