问题描述
我正在下载一个JSON数据。
I am having a JSON data like below.
{
"divisions": [{
"name": "division1",
"id": "div1",
"subdivisions": [{
"name": "Sub1Div1",
"id": "div1sub1",
"schemes": [{
"name": "Scheme1",
"id": "scheme1"
}, {
"name": "Scheme2",
"id": "scheme2"
}]
}, {
"name": "Sub2Div1",
"id": "div1sub2",
"schemes": [{
"name": "Scheme3",
"id": "scheme3"
}]
}
]
}]
}
将其读入TreeStore,但不能更改子字段( divisions
, subdivisions
,
)相同(例如, children
)。
I want to read this into a TreeStore, but cannot change the subfields ( divisions
, subdivisions
, schemes
) to be the same (eg, children
).
如何实现这一点?
推荐答案
当嵌套JSON加载到TreeStore中时,本质上通过递归调用加载子节点之间 TreeStore.fillNode()
方法和 NodeInterface.appendChild()
。
When nested JSON is loaded into a TreeStore, essentially the children nodes are loaded through a recursive calls between TreeStore.fillNode()
method and NodeInterface.appendChild()
.
实际检索每个节点的子字段在此行的 TreeStore.onNodeAdded()
中完成:
The actual retrieval of each node's children field is done within TreeStore.onNodeAdded()
on this line:
dataRoot = reader.getRoot(data);
读者的 getRoot()
在读者的 buildExtractors()
方法中动态创建,这是为了处理嵌套JSON中不同的子字段而需要重写的。这里是如何做的:
The getRoot()
of the reader is dynamically created in the reader's buildExtractors()
method, which is what you'll need to override in order to deal with varying children fields within nested JSON. Here is how it's done:
Ext.define('MyVariJsonReader', {
extend: 'Ext.data.reader.Json',
alias : 'reader.varijson',
buildExtractors : function()
{
var me = this;
me.callParent(arguments);
me.getRoot = function ( aObj ) {
// Special cases
switch( aObj.name )
{
case 'Bill': return aObj[ 'children' ];
case 'Norman': return aObj[ 'sons' ];
}
// Default root is `people`
return aObj[ 'people' ];
};
}
});
这将能够解释这样的JSON:
This will be able to interpret such JSON:
{
"people":[
{
"name":"Bill",
"expanded":true,
"children":[
{
"name":"Kate",
"leaf":true
},
{
"name":"John",
"leaf":true
}
]
},
{
"name":"Norman",
"expanded":true,
"sons":[
{
"name":"Mike",
"leaf":true
},
{
"name":"Harry",
"leaf":true
}
]
}
]
}
请参阅完全工作的代码。
See this JsFiddle for fully working code.
这篇关于加载具有不同子字段的JSON的TreeStore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!