How to generate Treeview from JSON data using java

2019-08-29 05:58发布

I am trying to create a treeview like structure from JSON data. Structure is quite simple, but the problem I am getting is while grouping the children under particular parents.

For example,

Input JSON data is :{'record':[{'sn':'Demo Sheet 1','vn':'Demo View 1'},{'sn':'Demo Sheet 11','vn':'Demo View 12'},{'sn':'Demo Sheet 2','vn':'Demo View 21'},{'sn':'Demo Sheet 1','vn':'Demo View 13'}],'recordcount':'4'}

Now, I want to display this data in below format :

  • Demo Sheet 1
    • Demo View 11
    • Demo View 12
    • Demo View 13
  • Demo Sheet 2
    • Demo View 21

In HTML, I have created a div like <div id="treeview"></div>.

Now using javascript I have to populate this div's innerHTML with the treeview list.

UPDATE : Count of Number of child Items should be displayed in the brackets of Parent Item, e.g. Demo Sheet 1 (3)

Any help to achieve this will be highly appreciated.

Thanks,

manishekhawat

1条回答
神经病院院长
2楼-- · 2019-08-29 06:32

It looks like you want to go from this structure:

{
    'record': [
        {'sn':'Demo Sheet 1','vn':'Demo View 11'},
        {'sn':'Demo Sheet 1','vn':'Demo View 12'},
        {'sn':'Demo Sheet 2','vn':'Demo View 21'},
        {'sn':'Demo Sheet 1','vn':'Demo View 13'}
    ],
    'recordcount':'4'
}

to this one:

{
    'Demo Sheet 1': [
        'Demo View 11',
        'Demo View 12',
        'Demo View 13'
    ],
    'Demo Sheet 2': [
        'Demo View 21'
    ]
}

I think the first place to start is to de-serialize your JSON string into the first object, then iterate over the 'record' array pulling out each element and creating a new array for each unique key, or adding to an existing array if that key already exists (e.g. 'Demo Sheet 1'). Once you've done that and discarded any extra data, you should end up with a data structure similar to the second one above, which should be very easy to generate mark-up for.

EDIT As an example of the above (using Douglas Crockford's JSON2 library, something like this:

var jsonObject = JSON.parse(jsonString /* your original json data */);
var newArrays = {};
var records = jsonObject.record;

for (var i = 0; i < records.length; i++) {
    if (!newArrays[records[i].sn]) {
        newArrays[records[i].sn] = [];
    }
    newArrays[records[i].sn].push(records[i].vn);
}

You now have the new data structure - how you mark it up is entirely up to you! See this fiddle for a working example.

Word of warning: I'd recommend adding some error handling to the above scenario, as you should never assume that the JSON data you're receiving will parse correctly.

EDIT 2 I've updated the fiddle to give an example of displaying it in the DOM. The function that adds it to the DOM is recursive (will work for any depth of nested arrays) just because I felt like writing it like that, but the function that transforms the initial JSON data isn't, so it doesn't really matter. :)

查看更多
登录 后发表回答