现阶段的项目是采用前后端分离的思想,前端使用的是Angular.JS,后端使用ABP框架,在后端我们通过WebAPI技术来向前端提供json数据。以前是通过MVC来写前端的代码,感觉后端有点在控制前端的节奏,一些少量的后端代码还是需要在HTML页面中写的,这次采用的这种模式,前端不需要写一点后端的C#代码,只负责写自己页面,至于说后端,只需要提供统一的json格式数据就可以,不需要管我前端如何展示。就是这样的情况,下面我们来看下如何将后端的数据json化。
后端数据转换为json
假设前端需要如下的数据格式:那么我们后端提供的josn格式就应该是这样的,这就利用到数据格式的转换了。
![](https://img-blog.csdnimg.cn/img_convert/8b408674d8952cbecf9e0acce9c9fe9a.png)
那么我们定义相关的类,看如何实现这样的格式。
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 ; } } |
我们后端需要进行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(); } |
我们可以看到只使用了一句转换代码。我们就可以得到具体的json数据。
![](https://img-blog.csdnimg.cn/img_convert/934356928318d92bf3300042932dd4ae.png)
解释
- 属性上面的标签 :[JsonProperty("id")]
意思是在json过程中将大写的Id转换为小写的。其余的意思一样。
1 | childrenTree.Childrens = new List<Tree2ChildrenView>(); |
难道我每次都要写这句吗。我们可以放到构造函数中去:
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); |
不需要再去实例化它,因为它自己调用的时候就自动实例化了。