現(xiàn)階段的項目是采用前后端分離的思想,前端使用的是Angular.JS,后端使用ABP框架,在后端我們通過WebAPI技術(shù)來向前端提供json數(shù)據(jù)。以前是通過MVC來寫前端的代碼,感覺后端有點在控制前端的節(jié)奏,一些少量的后端代碼還是需要在HTML頁面中寫的,這次采用的這種模式,前端不需要寫一點后端的C#代碼,只負(fù)責(zé)寫自己頁面,至于說后端,只需要提供統(tǒng)一的json格式數(shù)據(jù)就可以,不需要管我前端如何展示。就是這樣的情況,下面我們來看下如何將后端的數(shù)據(jù)json化。
后端數(shù)據(jù)轉(zhuǎn)換為json
假設(shè)前端需要如下的數(shù)據(jù)格式:那么我們后端提供的josn格式就應(yīng)該是這樣的,這就利用到數(shù)據(jù)格式的轉(zhuǎn)換了。

那么我們定義相關(guān)的類,看如何實現(xiàn)這樣的格式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | /// <summary>
/// 第一大類
/// </summary>
public class TreeView
{
[JsonProperty( "id" )]
public int Id { get; set ; }
[JsonProperty( "text" )]
public string Text { get; set ; }
[JsonProperty( "children" )]
public IList<TreeChildrenView> Childrens{ get; set ; }
}
/// <summary>
/// 第一大類中包含的第二大類
/// </summary>
public class TreeChildrenView
{
[JsonProperty( "id" )]
public int Id { get; set ; }
[JsonProperty( "text" )]
public string Text { get; set ; }
[JsonProperty( "children" )]
public IList<Tree2ChildrenView> Childrens { get; set ; }
}
/// <summary>
/// 第二大類包含的第三大類
/// </summary>
public class Tree2ChildrenView
{
[JsonProperty( "id" )]
public int Id { get; set ; }
[JsonProperty( "text" )]
public string Text { get; set ; }
}
|
我們后端需要進(jìn)行josn化,就需要引用Newtonsoft.Json此類庫。
1 | JsonConvert.SerializeObject();
|
下面看我們的代碼。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | static void Main(string[] args)
{
var treeView = new TreeView()
{
Id=1,
Text = "陜西" ,
};
var childrenTree = new TreeChildrenView()
{
Id=2,
Text = "寶雞市"
};
var chchTree = new Tree2ChildrenView()
{
Id=3,
Text = "眉縣"
};
childrenTree.Childrens = new List<Tree2ChildrenView>();
childrenTree.Childrens. Add (chchTree);
treeView.Childrens=new List<TreeChildrenView>();
treeView.Childrens. Add (childrenTree);
string json = JsonConvert.SerializeObject(treeView);
Console.WriteLine(json);
Console.ReadLine();
}
|
我們可以看到只使用了一句轉(zhuǎn)換代碼。我們就可以得到具體的json數(shù)據(jù)。

解釋
- 屬性上面的標(biāo)簽 :[JsonProperty("id")]
意思是在json過程中將大寫的Id轉(zhuǎn)換為小寫的。其余的意思一樣。
1 | childrenTree.Childrens = new List<Tree2ChildrenView>();
|
難道我每次都要寫這句嗎。我們可以放到構(gòu)造函數(shù)中去:
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class TreeView
{
public TreeView()
{
this.Childrens=new List<TreeChildrenView>();
}
[JsonProperty( "id" )]
public int Id { get; set ; }
[JsonProperty( "text" )]
public string Text { get; set ; }
[JsonProperty( "children" )]
public IList<TreeChildrenView> Childrens{ get; set ; }
}
|
這樣我們每次就直接使用就OK了。
1 | childrenTree.Childrens. Add (chchTree);
|
不需要再去實例化它,因為它自己調(diào)用的時候就自動實例化了。
|