我通过PUT从angularJS发送一个JSON对象到c#,它有一个属性名和一个值。
我正在尝试为每个属性循环并读取名称和值,但它失败了。我已成功通过以下代码只读取名称或仅读取值:
Newtonsoft.Json.Linq.JObject cbpcs = pricestopsale.cbPricegroups;
foreach (string pricegroupInfo in cbpcs.Properties().Select(p => p.Value).ToList())
{
// I want to be able to do something like this inside here
if(pricegroupInfo.Value == "Something") {
// do stuff
}
}
在上面的例子中,pricegroupInfo有值,如果我改变.Select(p => p.Name).ToList())
,我得到属性的名称。
如果我想在循环中获取名称和值,我该怎么办?
更新1:属性名称对我来说是未知的,它是动态生成的,因此我事先并不知道属性名称。
更新2:我希望能够将值和名称作为循环内的字符串进行比较。
尝试在select中使用匿名对象。
Newtonsoft.Json.Linq.JObject cbpcs = pricestopsale.cbPricegroups;
foreach (var pricegroupInfo in cbpcs.Properties().Select(p => new { p.Value, p.Name }).ToList())
{
// read the properties like this
var value = pricegroupInfo.Value;
var name = pricegroupInfo.Name;
if(pricegroupInfo.Value.ToObject<string>() == "foo")
{
Console.WriteLine("this is true");
}
}
Reference: JObject.Properties Method
Newtonsoft.Json.Linq.JObject cbpcs = pricestopsale.cbPricegroups;
foreach (var pricegroupInfo in cbpcs.Properties())
{
if(pricegroupInfo.Name == "propName" // your property name
&& pricegroupInfo.Value.ToString() == "something") { // your value
// do stuff
}
}
如你所见,它返回IEnumerable<JProperty>
,使用可以迭代并利用获取属性Name
和Value
试试这个
foreach(var prop in cbpcs.GetType().GetProperties()) {
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));}