我正在解析一些JSON到csv。我有我的課的設置如下:C#JSON.net null嵌套對象
public class SearchObj
{
public class Property
{
public string __cloudera_internal__hueLink { get; set; }
}
public class root
{
public string blockSize { get; set; }
public string clusteredByColNames { get; set; }
public string compressed { get; set; }
public string created { get; set; }
public string dataType { get; set; }
public string deleted { get; set; }
public Property properties { get; set; }
}
}
再後來我與此對象的工作:
string json = infile.ReadToEnd();
var rootObject = JsonConvert.DeserializeObject<List<SearchObj.root>>(json);
for (int i = 0; i < rootObject.Count; i++)
{
//holding is a dict that holds json key/value pairs,
//arg[1] is a prefix for key:value pairs, in this case, no prefix
//so a nested key goes into dictionary as key.nestedkey
ResolveTypeAndValue(rootObject[i], "", holding);
}
當然,我們需要看到的解決方法的代碼:
private static void ResolveTypeAndValue(object obj, string name, Dictionary<string, string> storage)
{
//this next line is the error problem
var type = obj.GetType();
foreach (var p in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
if (p.PropertyType.IsClass && p.PropertyType != typeof(string))
{
var currentObj = p.GetValue(obj);
ResolveTypeAndValue(currentObj, p.Name + ".", storage);
}
else
{
string val = "";
if (p.GetValue(obj) != null)
{
val = p.GetValue(obj).ToString();
}
storage.Add(name + p.Name, val);
}
}
}
所以當我運行這個時,我得到了一個「未處理的異常類型'System.NullReferenceException'發生在.....」中,標記了上面的行。我相信這是因爲大多數時候,「屬性」鍵是空的。實際上,儘管嵌套的「合適」鍵只有一個鍵:「__cloudera_internal__hueLink」的鍵值對和鍵值(本質上是文本)作爲鍵值。
我在不同的JSON模式集上成功運行了這段代碼,但沒有問題 - 但對於我來說,我無法弄清楚如何基本上將鍵/值對設置爲「properties」:「null 「或」properties .__ cloudera_internal__hueLink「:」值字段「。以前嵌套的json對象總是有一些東西,即使它從入口到入口都是不同的。
您可能需要在新手級別提供幫助,我只在工作中使用C#,因爲它是我可用的所有東西 - 但很明顯,我已經在這裏找到了一些關於處理JSON對象的東西,但是這其中有我陷入相當困難的
我要麼得到根本不填充錯誤或「屬性」,並拋出一個關鍵找不到錯誤
你可以提供一些JSON嗎? – Kamen