[英]Getting property from c# anonymous object
在服務器上,我得到 JSON 對象。 我使用 JsonConvert 將它們反序列化為匿名對象。 然后我想訪問成員,但我不能做這樣的事情:
object a = jsonObj.something.something.else;
所以我創建了以下內容,目的是能夠使用選擇器字符串數組訪問成員。 但是,這里的 getProperty() 總是返回 null。 有任何想法嗎?
private object recGetProperty(object currentNode, string[] selectors, int index) {
try {
Type nodeType = currentNode.GetType();
object nextNode = nodeType.GetProperty(selectors[index]);
if (index == (selectors.Length - 1)) {
return nextNode;
}
else {
return recGetProperty(nextNode, selectors, index + 1);
}
}
catch (Exception e) {
return null;
}
}
private object getProperty(object root, string[] selectors) {
return recGetProperty(root, selectors, 0);
}
JsonConvert.DeserializeObject
不會反序列化為匿名對象(我猜,你不使用JsonConvert.DeserializeAnonymousType )。 根據 json,它返回JObject
或JArray
。
1.由於JObject實現了IDictionary<string, JToken>
你可以這樣使用
string json = @"{prop1:{prop2:""abc""}}";
JObject jsonObj = JsonConvert.DeserializeObject(json) as JObject;
Console.WriteLine(jsonObj["prop1"]["prop2"]);
或者
string str = (string)jsonObj.SelectToken("prop1.prop2");
2.如果要使用dynamic關鍵字,那么
dynamic jsonObj = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonObj.prop1.prop2);
兩種方式都會打印abc
我的代碼
Dictionary<string, object> dictionaryObject = new Dictionary<string, object>();
if (anonymousObject is string)
{
dictionaryObject = JsonConvert.DeserializeObject<Dictionary<string,object>>((string)anonymousObject);
}
if (!dictionaryObject.ContainsKey(propertyName))
{
throw new Exception($"property name '{propertyName}' not found");
}
object value = dictionaryObject[propertyName];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.