2013-07-11 41 views
-2

我有一個如下所示的JSON結構。從C#中的JSON對象中獲取值

{"name":"user1","param":{"showid":"test"}} 

我會將JSON結構的值傳遞給JSON對象的值將被取出的程序。 但是,每個JSON對象的鍵值都不相同。 所以我不能創建JSON對象的結構來檢索值。

ie:下一次JSON對象可能如下所示。

{"name1":"user2","param1":{"showname":"test1"}} 

如何從C#中的JSON結構迭代鍵值對?

+1

解析它與任何json庫嗎? Google受傷了? – wudzik

+0

JSON結構將在Javascript中創建,另一方面我需要在C#中迭代它,而不使用任何第三方引用。 –

+0

如果不使用第三方引用,您需要閱讀json規範並編寫自己的解析器。但我認爲這不是最好的主意,爲什麼不能使用第三方? – wudzik

回答

4

您可以使用System.Web.Script.Serialization.JavaScriptSerializer(System.Web.Extensions.dll)並將其加載到數據類型「dynamic」中,然後可以像字典一樣訪問屬性。

或者您可以使用反射來查找可用的屬性/字段,並獲取字段/屬性的值。

public static Dictionary<string, object> ToPropertyDictionary(this object obj) 
{ 
    var dictionary = new Dictionary<string, object>(); 
    foreach (var propertyInfo in obj.GetType().GetProperties()) 
     if (propertyInfo.CanRead && propertyInfo.GetIndexParameters().Length == 0) 
      dictionary[propertyInfo.Name] = propertyInfo.GetValue(obj, null); 
    return dictionary; 
} 
+0

我的程序在.net 3.5中開發,其中動態關鍵字不受支持。您能否提供一些示例代碼,瞭解如何使用反射來實現此目的? –

+0

public class JsonDeserializer private IDictionary jsonData {get;組; } public static Dictionary ToPropertyDictionary(this object obj) { var dictionary = new Dictionary (); foreach(var propertyInfo in obj.GetType()。GetProperties()) if(propertyInfo.CanRead && propertyInfo.GetIndexParameters()。Length == 0) dictionary [propertyInfo.Name] = propertyInfo.GetValue(obj,null) ; 返回字典; }你能弄清楚爲什麼在這裏得到錯誤? –

+0

@ user833985:obj == null? –