我从请求中收到一个Json对象,我想迭代它的属性,并执行以下操作:
如果属性等于“EN”而不是得到它的值。
我在网上看到的解决方案都与GetProperties / GetProperty方法有关但我尝试了两种方法,但没有一种方法有效。 这应该是“简单”的东西,但我认为我在这里遗漏了一些东西。
//Deserializing the object
ExpandoObject deserializedContent = JsonConvert.DeserializeObject<ExpandoObject>(obj.ToString(), new ExpandoObjectConverter());
dynamic deserializedDynamicContent = deserializedContent;
//Tries
var value = deserializedDynamicContent.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
var value = deserializedDynamicContent.GetType().GetProperty("ES").GetValue();
在这两种情况下我得到零属性。
如果我执行下面的代码,我只能获取值,但如果添加了新语言,这将使我无法编码。
deserializedDynamicContent.EN,
deserializedDynamicContent.ES or
deserializedDynamicContent.PT
我在这里做错了什么?
{
"EN":[{"Id":1,"Name":"One"},{"Id":2,"Name":"Two"},{"Id":3,"Name":"Tree"}],
"ES":[{"Id":1,"Name":"Uno"},{"Id":2,"Name":"Dos"},{"Id":3,"Name":"Tres"}],
"PT":[{"Id":1,"Name":"Um"},{"Id":2,"Name":"Dois"},{"Id":3,"Name":"Três"}]
}
答案 0 :(得分:0)
我不确定您要实现的目标,但由于ExpandoObject
实现了IDictionary<string,object>
,您应该能够做到这样的事情:
var expando = JsonConvert.DeserializeObject<ExpandoObject>(yourJson);
var dict = (IDictionary<string, object>)expando;
// look for a particular key...
object value;
if (dict.TryGetValue("EN", out value))
{
Console.WriteLine("Key exists!");
var list = (List<dynamic>)value;
Console.WriteLine(string.Join(",", list.Select(x => "{" + x.Id + "," + x.Name + "}")));
}
// or enumerate the entire dictionary...
foreach (var kvp in dict)
{
var list = (List<dynamic>)kvp.Value;
Console.WriteLine(
kvp.Key + ":" + string.Join(",", list.Select(x => "{" + x.Id + "," + x.Name + "}")));
}