动态更改Json格式

时间:2014-02-05 13:48:57

标签: json dynatree

我的JSON会返回类似这样的内容

        {
    data: "Business & Investing (0)",
    attr: {
    id: "91",
    rel: "file",
    dataitem: null,
    datatext: null
    },
    children: [ ]
    },
    {
    data: "Stock Exchange & Money (0)",
    attr: {
    id: "92",
    rel: "file",
    dataitem: null,
    datatext: null
    },
    children: [ ]
    },

我希望将“数据”改为“标题”,然后将其传递给视图

    {
title: "Business & Investing (0)",
attr: {
id: "91",
rel: "file",
dataitem: null,
datatext: null
},
children: [ ]
},
{
title: "Stock Exchange & Money (0)",
attr: {
id: "92",
rel: "file",
dataitem: null,
datatext: null
},
children: [ ]
},

我的Dynatree:

  function CreateCatTree(filter) {

        $("#res_catBar").dynatree({
            postProcess: function (data, dataType) {
                alert("hey");

            },
            initAjax: {

                type: "GET",                
                cache:false,
                url: '@Url.Action("Catalog")',
                data: {
                    filter:filter
                },
            },
            onActivate: function (node) {

                var id = node.data.attr.id;
                event.preventDefault();
                 retrieveCatalog(id);
                     return false;
            }          
        });

    }

3 个答案:

答案 0 :(得分:1)

你可以在JS中试试这个:

if (yourJSON.hasOwnProperty("data")) {
    yourJSON["title"] = yourJSON["data"];
    delete yourJSON["data"];
}

答案 1 :(得分:1)

因为您似乎使用Dynatree:

你也可以在JavaScript中实现postProcess(data, dataType)回调,并在传递给Dynatree之前修改那里的Ajax结果。

答案 2 :(得分:1)

您应该创建自己的具有已定义属性集的类,然后可以通过Newtownsoft JSON进行序列化。

我有一个TreeNode.cs

public class TreeNode
{

    [JsonProperty("title")]
    public string title { get; set; }

这是通过Web服务调用的:

 List<TreeNode> myTaskListObj = new List<TreeNode>();

然后根据需要反序列化或序列化数据:

        //De Serialize
        myTaskListObj = JsonConvert.DeserializeObject<List<TreeNode>>(jsonString);

        //Serialize 
        jsonString = JsonConvert.SerializeObject(myTaskListObj, Formatting.Indented);

希望这有帮助。