【问题标题】:How to convert a hierarchy list to json如何将层次结构列表转换为 json
【发布时间】:2011-07-23 06:24:41
【问题描述】:

我正在使用 ASP.NET MVC3

我有一个这种类型的层次结构列表:

public class TreeNode
{
public int id;
public int title;
public int parentid;
}
var myHierarchyList=new List<TreeNode>();
//(the tree has a root with id=1 and parentid=0 and title=root)

我需要一个函数来从 myHierarchyList 生成 json 数据。像这样的东西:

[{
    "id":1,
    "text":"cat1",
    "childrens":[{
        "id":2,
        "text":"cat2"
    },{
        "id":3,
        "text":"cat3",
        "childrens":[{
            "id":4,
            "text":"cat4"
        },{
            "id": 8,
            "text":"cat5"
        }]
    }]
}]

请帮助我。 谢谢。

【问题讨论】:

  • JavaScriptSerializer 输出什么?
  • 我自己有个想法,但是不知道怎么实现!这个想法是定义一个新类,如: public class node{public int id;公共 int 标题; public List childs} 并将树构建到其中。
  • 您是否尝试过使用 JavaScriptSerializer 类?如果可行,重新发明轮子也没用。

标签: c# json asp.net-mvc-3 hierarchy


【解决方案1】:

看看复合设计模式。这允许您建立不同对象的层次结构并递归循环并使用字符串生成器生成 xml、json html 等。

【讨论】:

    【解决方案2】:

    可能是这样的:

    namespace MyNameSpace
    {
        using System.Runtime.Serialization.Json;
        using System.IO;
        using System.Text;
    
        public static class JsonExtensions
        {
            public static string JsonSerialize<T>(this T obj) where T : class
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                using (MemoryStream stream = new MemoryStream())
                {
                    serializer.WriteObject(stream, obj);
                    return Encoding.Default.GetString(stream.ToArray());
                }
            }
    
            public static T JsonDeserialize<T>(this T obj, string json) where T : class
            {
                using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json)))
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                    return serializer.ReadObject(stream) as T;
                }
            }
        }
    }
    
    
    ...................
    
    
    void somefuntion()
    {
        MyObject myObject = new MyObject()
        ...Do stuff to myObject .........
        ............
    
        // Get myObject as a Json String
        string json = myObject.JsonSerialize();
    }
    

    【讨论】:

    • ...Do stuff to myObject ......... 部分,也是我的问题的一部分!这是构建层次结构对象的递归方式:dhirajranka.com/?p=30 请根据此更新您的答案。所以我会把你的答案标记为答案:)
    猜你喜欢
    • 2019-10-08
    • 2023-03-31
    • 2022-07-15
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    相关资源
    最近更新 更多