I am parsing some JSON to csv. I have my class setup as follows:
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);
}
}
}
Change the ResolveTypeAndValue
function to this:
private static void ResolveTypeAndValue(object obj, string name, Dictionary<string, string> storage)
{
if (obj == null)
{
storage.Add(name, null);
return;
}
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); // removed this: '+ "."'
}
else
{
string val = "";
if (p.GetValue(obj) != null)
{
val = p.GetValue(obj).ToString();
}
storage.Add(name + "." + p.Name, val); // added this: '+ "."'
}
}
}