假设前端需要如下的数据格式:那么我们后端提供的josn格式就应该是这样的,这就利用到数据格式的转换了。
那么我们定义相关的类,看如何实现这样的格式。
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
|
///
/// 第一大类
///
public
class TreeView
{
[JsonProperty(
"id"
)]
public
int
Id { get;
set
; }
[JsonProperty(
"text"
)]
public
string Text { get;
set
; }
[JsonProperty(
"children"
)]
public
IList
set
; }
}
///
/// 第一大类中包含的第二大类
///
public
class TreeChildrenView
{
[JsonProperty(
"id"
)]
public
int
Id { get;
set
; }
[JsonProperty(
"text"
)]
public
string Text { get;
set
; }
[JsonProperty(
"children"
)]
public
IList
set
; }
}
///
/// 第二大类包含的第三大类
///
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
childrenTree.Childrens.
Add
(chchTree);
treeView.Childrens=new List
treeView.Childrens.
Add
(childrenTree);
string json = JsonConvert.SerializeObject(treeView);
Console.WriteLine(json);
Console.ReadLine();
}
|
我们可以看到只使用了一句转换代码。我们就可以得到具体的json数据。
意思是在json过程中将大写的Id转换为小写的。其余的意思一样。
1
|
childrenTree.Childrens = new List
|
难道我每次都要写这句吗。我们可以放到构造函数中去:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public
class TreeView
{
public
TreeView()
{
this.Childrens=new List
}
[JsonProperty(
"id"
)]
public
int
Id { get;
set
; }
[JsonProperty(
"text"
)]
public
string Text { get;
set
; }
[JsonProperty(
"children"
)]
public
IList
set
; }
}
|
这样我们每次就直接使用就OK了。
1
|
childrenTree.Childrens.
Add
(chchTree);
|
不需要再去实例化它,因为它自己调用的时候就自动实例化了。