serialise a c# datatable with a hierarchy as json heirachy

萝らか妹 提交于 2020-02-25 13:52:15

问题


I have a dataTable with the following data in it:

Parent  Child
Dan     Heidi
Dan     Lauren
Alan    Dan
Daphne  Alan
Alan    Lorna
Alan    Tim

I want to output the following json:

[
  {
    'name': 'Daphne',
    'children': [
      {
        'name': 'Alan',
        'children': [
          {
            'name': 'Dan',
            'children': [
              {
                'name': 'Heidi'
              },
              {
                'name': 'Lauren'
              }
            ]
          },
          {
            'name': 'Tim'
          },
          {
            'name': 'Lorna'
          }
        ]
      }
    ]
  }
]

I've used the json.net serialiser to serialse one level in the hierarchy, I would have thought this was a common problem. Is there a simple way to convert a datTable with a hierarchy to a json string with a hierarchy?

I guess the key bit is identifying how many and which levels there are in the hierarchy, ive looked at the hierarchyid datatype in sql server but it seems a bit messy to need that.

Thanks, Dan


回答1:


Here's example dataTable serialization

Or you can create IEnumerable<ComplexData> from dataTable and serialise



来源:https://stackoverflow.com/questions/20846897/serialise-a-c-sharp-datatable-with-a-hierarchy-as-json-heirachy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!