Json对象内部的对象通过asp.net c#从sql server
本文关键字:对象 server net sql 内部 Json asp | 更新日期: 2023-09-27 17:50:51
我正在使用jtree插件,我需要json格式,这是内部对象。
这是我的输出:
[{"id":"1","text":"Document Management","parent":"#","icon":"fa fa-table","selected":1}
,{"id":"2","text":"Document List","parent":"1","icon":"fa fa-list","selected":1}
,{"id":"7","text":"Hazard","parent":"#","icon":"fa fa-file-text","selected":1}]
这就是我需要的:
[{"id":"1","text":"Document Management","parent":"#","icon":"fa fa-table",state: { opened: true, selected: true }}}
,{"id":"2","text":"Document List","parent":"1","icon":"fa fa-list",state: { opened: true, selected: true }}}
,{"id":"7","text":"Hazard","parent":"#","icon":"fa fa-file-text",state: { opened: true, selected: true }}}]
和这些是我的c#和js代码,创建json序列化和树视图;c#
[WebMethod]
public static string Menu()
{
ClassSystemAccessPolicy classDocumentPolicy = new ClassSystemAccessPolicy();
DataTable dt = new DataTable();
dt = classDocumentPolicy.Permission_Load().Tables[0];
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
js
var MenuTree = function () {
$.ajax({
type: "POST",
url: "Permission.aspx/Menu",
contentType: "application/json",
dataType: "json",
success: function (data) {
var menu$json = JSON.parse(data.d);
$('#tree_menu').jstree({
'plugins': ["wholerow", "checkbox", "types"],
'core': {
"themes": {
"responsive": false
},
'data': menu$json
}
});
console.log(menu$json)
},
error: function () {
console.log('err')
}
});
如何像state: { selected: true }
那样序列化?
您需要为此创建自己的DTO(数据传输对象)
public class JSTreeDTO
{
public string id{get;set;}
public string text{get;set;}
public string text{get;set;}
public string parent {get;set;}
public string icon{get;set;}
public StateDTO state{get;set;}
}
public class StateDTO
{
public bool opened{get;set;}
public bool selected{get;set;}
}
然后在循环
中创建它List<JSTreeDTO> treeList=new List<JSTreeDTO>();
foreach (DataRow dr in dt.Rows)
{
JSTreeDTO node=new JSTreeDTO();
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
node.id=dr["id"];//etc
node.state=new StateDTO();
node.state.opened=true;//based on your logic
}
treeList.Add(node);
return serializer.Serialize(treeList);
}