从平面列表创建递归对象

时间:2015-08-20 22:21:04

标签: c# json dictionary serialization

我有一个列表如下所示:

        List<MenuItem> menuItems = new List<MenuItem>();
        menuItems.Add(new MenuItem() { SiteMenuId = 1, ParentId = null, MenuName = "Menu", Url = null, SiteId = 1 });
        menuItems.Add(new MenuItem() { SiteMenuId = 2, ParentId = 1, MenuName = "aaa", Url = "aaa", SiteId = 1 });
        menuItems.Add(new MenuItem() { SiteMenuId = 3, ParentId = 1, MenuName = "bbb", Url = null, SiteId = 1 });
        menuItems.Add(new MenuItem() { SiteMenuId = 4, ParentId = 3, MenuName = "ccc", Url = "ccc", SiteId = 1 });
        menuItems.Add(new MenuItem() { SiteMenuId = 5, ParentId = 3, MenuName = "ddd", Url = "ddd", SiteId = 1 });
        menuItems.Add(new MenuItem() { SiteMenuId = 6, ParentId = 1, MenuName = "eee", Url = "eee", SiteId = 1 });

是否可以将此数据结构转换为可以序列化为以下json的格式:

{
    "Menu": {
        "aaa": "aaa",
        "bbb": {
            "ccc": "ccc",
            "ddd": "ddd"
        },
        "eee": "eee"
    }
}

如果答案是肯定的,我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以尝试创建这样的类

public class MenuItemTr
{

 public MenuItemTr
 {
    this.MenuItems= new List <MenuItem>
 }
public int SiteMenuId {get; set;}
public int ParentId {get; set;}
public string MenuName {get; set;}
public string Url {get; set;}
public int SiteId {get; set;}
public List <MenuItemTr> MenuItems {get; set;}
}

然后将其解析为树

var MenuItem = menuItems.GenerateTree(c => c.SiteMenuId, c => c.ParentId);

并使用此线程中的此解决方案Nice & universal way to convert List of items to Tree

public static IEnumerable<TreeItem<T>> GenerateTree<T, K>(
        this IEnumerable<T> collection,
        Func<T, K> id_selector,
        Func<T, K> parent_id_selector,
        K root_id = default(K))
    {
        foreach (var c in collection.Where(c => parent_id_selector(c).Equals(root_id)))
        {
            yield return new TreeItem<T>
            {
                Item = c,
                Children = collection.GenerateTree(id_selector, parent_id_selector, id_selector(c))
            };
        }
    }
}

答案 1 :(得分:1)

您可以考虑使用Json.NET

Json.NET将任何IDictionary序列化为JSON key/value pair object - 但转换为Dictionary<string, object>然后序列化会有问题,因为.Net字典是unordered,而您(和可能)在序列化为JSON时,希望保留 MenuItem个对象的相对顺序。因此,使用JObject手动转换为LINQ to JSON对象的树是有意义的,因为Json.NET保留了对象属性的顺序。

因此你会这样做:

    public static string CreateJsonFromMenuItems(IList<MenuItem> menuItems)
    {
        return new JObject
        (
            menuItems.ToTree(
                m => (int?)m.SiteMenuId,
                m => m.ParentId, m => new JProperty(m.MenuName, m.Url),
                (parent, child) =>
                {
                    if (parent.Value == null || parent.Value.Type == JTokenType.Null)
                        parent.Value = new JObject();
                    else if (parent.Value.Type != JTokenType.Object)
                        throw new InvalidOperationException("MenuItem has both URL and children");
                    child.MoveTo((JObject)parent.Value);
                })
        ).ToString();
    }

(注意,如果MenuItem同时包含非空Url和子集合,则此方法会抛出异常。)

它使用以下扩展方法:

public static class JsonExtensions
{
    public static void MoveTo(this JToken token, JObject newParent)
    {
        if (newParent == null)
            throw new ArgumentNullException();
        var toMove = token.AncestorsAndSelf().OfType<JProperty>().First(); // Throws an exception if no parent property found.
        if (toMove.Parent != null)
            toMove.Remove();
        newParent.Add(toMove);
    }
}

public static class RecursiveEnumerableExtensions
{
    static bool ContainsNonNullKey<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
    {
        if (dictionary == null)
            throw new ArgumentNullException();
        return key == null ? false : dictionary.ContainsKey(key); // Dictionary<int?, X> throws on ContainsKey(null)
    }

    public static IEnumerable<TResult> ToTree<TInput, TKey, TResult>(
        this IEnumerable<TInput> collection,
        Func<TInput, TKey> idSelector,
        Func<TInput, TKey> parentIdSelector,
        Func<TInput, TResult> nodeSelector,
        Action<TResult, TResult> addMethod)
    {
        if (collection == null || idSelector == null || parentIdSelector == null || nodeSelector == null || addMethod == null)
            throw new ArgumentNullException();
        var list = collection.ToList(); // Prevent multiple enumerations of the incoming enumerable.
        var dict = list.ToDictionary(i => idSelector(i), i => nodeSelector(i));
        foreach (var input in list.Where(i => dict.ContainsNonNullKey(parentIdSelector(i))))
        {
            addMethod(dict[parentIdSelector(input)], dict[idSelector(input)]);
        }
        return list.Where(i => !dict.ContainsNonNullKey(parentIdSelector(i))).Select(i => dict[idSelector(i)]);
    }
}

工作fiddle