目前我有以下Json,我将其转换为普通对象C#类。在我的普通对象类中,我将它们放在ModelMock类中,试图访问属性"name"one_answers"value"。但我无法访问,我得到并出错。我得到的错误:"列表"不包含"名称"one_answers"值"的定义
这是供参考的Json:
{
"matchActionsReasons": [
{
"name": "False positive",
"value": -2147483648
},
{
"name": "Acceptable risk",
"value": -2147483647
},
{
"name": "Manager approval",
"value": -2147483646
}
]
}
这是我的模型类:
public class ModelMock
{
public static ModelMock SaveSettingsModel()
{
return new ModelMock
{
matchActionsReasons =new List<MatchActionsReason>
{
name = "False positive", **//Geting the error here**
value = -2147483648 **//Geting the error here**
}
};
}
public class MatchActionsReason
{
public string name { get; set; }
public int value { get; set; }
}
public List<MatchActionsReason> matchActionsReasons { get; set; }
}
您必须创建和添加类型为MatchActionsReason
:的对象
// Using a collection initializer for the list
// and object initializers for the items
matchActionsReasons = new List<MatchActionsReason>{
new MatchActionsReason{ name = "False positive", value = -2147483648 },
new MatchActionsReason{ name = "Acceptable risk", value = -2147483647 },
new MatchActionsReason{ name = "Manager approval", value = -2147483646 }
};
或
// Using Add
matchActionsReasons = new List<MatchActionsReason>();
matchActionsReasons.Add(
new MatchActionsReason{ name = "False positive", value = -2147483648 }
);
matchActionsReasons.Add(
new MatchActionsReason{ name = "Acceptable risk", value = -2147483647 }
);
matchActionsReasons.Add(
new MatchActionsReason{ name = "Manager approval", value = -2147483646 }
);
List<T>
类本身不具有name
和value
属性。除其他外,它具有Count
特性。
您可以访问列表中元素的成员,如下所示:
string s = matchActionsReasons[1].name; // ==> "Acceptable risk"
或
MatchActionsReason mar = matchActionsReasons[1];
string s = mar.name; // ==> "Acceptable risk"
你必须这样写:
matchActionsReasons =new List<MatchActionsReason>
{
new MatchActionReason
{
name = "False positive",
value = -2147483648
},
add more instances here...
}
所以完整的样本看起来是这样的:
public class ModelMock
{
public static ModelMock SaveSettingsModel()
{
return new ModelMock
{
matchActionsReasons =new List<MatchActionsReason>
{
new MatchActionReason
{
name = "False positive",
value = -2147483648
},
new MatchActionReason
{
name = "Another False One",
value = -111111111
},
add more instances here...
}
};
}
public class MatchActionsReason
{
public string name { get; set; }
public int value { get; set; }
}
public List<MatchActionsReason> matchActionsReasons { get; set; }
}
原因是当你做新的列表{把新的实例放在这里}
因此,您将要添加到列表中的实例放在括号之间。
这被称为集合初始值设定项。
这是Microsoft针对Obejct和Collection Initializers 的文档
您需要向列表中添加一个新的MatchActionsReason对象。如下图所示。
matchActionsReasons = new List<MatchActionsReason>();
matchActionsReasons.Add(new MatchActionsReason(){ name = "foo", value = 115 });