我有一個如下所示的JSON結構。從C#中的JSON對象中獲取值
{"name":"user1","param":{"showid":"test"}}
我會將JSON結構的值傳遞給JSON對象的值將被取出的程序。 但是,每個JSON對象的鍵值都不相同。 所以我不能創建JSON對象的結構來檢索值。
ie:下一次JSON對象可能如下所示。
{"name1":"user2","param1":{"showname":"test1"}}
如何從C#中的JSON結構迭代鍵值對?
我有一個如下所示的JSON結構。從C#中的JSON對象中獲取值
{"name":"user1","param":{"showid":"test"}}
我會將JSON結構的值傳遞給JSON對象的值將被取出的程序。 但是,每個JSON對象的鍵值都不相同。 所以我不能創建JSON對象的結構來檢索值。
ie:下一次JSON對象可能如下所示。
{"name1":"user2","param1":{"showname":"test1"}}
如何從C#中的JSON結構迭代鍵值對?
您可以使用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;
}
我的程序在.net 3.5中開發,其中動態關鍵字不受支持。您能否提供一些示例代碼,瞭解如何使用反射來實現此目的? –
public class JsonDeserializer private IDictionary
@ user833985:obj == null? –
解析它與任何json庫嗎? Google受傷了? – wudzik
JSON結構將在Javascript中創建,另一方面我需要在C#中迭代它,而不使用任何第三方引用。 –
如果不使用第三方引用,您需要閱讀json規範並編寫自己的解析器。但我認爲這不是最好的主意,爲什麼不能使用第三方? – wudzik