一个层级结构很深的json对象
下面的代码是JSON扁平化的帮助类:声明:
代码如下:
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace MongoDBAccess
{
public class JsonHelper
{
private readonly List _keys = new List();
public string ToFlat(JObject obj, string parent)
{
string result = null;
foreach (var item in obj)
{
if (typeof(JObject) == item.Value.GetType())
{
var child = (JObject)item.Value;
var tmp = ToFlat(child, item.Key);
result += tmp;
}
else if (typeof(JArray) == item.Value.GetType())
{
var jarray = (JArray)item.Value;
if (jarray.Count == 0 && !_keys.Contains(item.Key))
{
result += string.Format("'{0}':{1},", item.Key, new JArray());
_keys.Add(item.Key);
}
else
{
foreach (var jitem in jarray)
{
if (jitem.HasValues)
{
var jchild = (JObject)jitem;
string tmp = ToFlat(jchild, item.Key);
result += tmp;
}
else if(!_keys.Contains(item.Key))
{
result += string.Format("'{0}':{1},", item.Key, new JArray(){jitem});
_keys.Add(item.Key);
}
}
}
}
else
{
var value = item.Value ?? " ";
if (string.IsNullOrEmpty(parent) && !_keys.Contains(item.Key))
{
result += string.Format("'{0}':\"{1}\",", item.Key, value);
_keys.Add(item.Key);
}
else if (!_keys.Contains(parent + "_" + item.Key))
{
result += string.Format("'{0}_{1}':'{2}',", parent, item.Key, value);
_keys.Add(parent + "_" + item.Key);
}
}
}
return result;
}
}
}