Jil - Ignore & Custom Element Name

使用 Jil 處理 JSON 時,如果要在序列化時忽略處理某特定屬性,可在其屬性加上 IgnoreDataMemberAttribute,像是下面這樣:

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
using System;
using System. Runtime.Serialization ;
using Jil;

namespace ConsoleApplication10
{
class Program
{
static void Main( string[] args )
{
var larry = new Person
{
Name = "Larry Nung",
NickName = "Larry"
};

Console.WriteLine (JSON. Serialize(larry ));
}

public class Person
{
[ DataMember]
public String Name { get; set ; }

[ IgnoreDataMember]
public String NickName { get; set ; }
}
}
}


或是帶上 JilDirectiveAttribute,指定 Ignore:

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
using System;
using System. Runtime.Serialization ;
using Jil;

namespace ConsoleApplication10
{
class Program
{
static void Main( string[] args )
{
var larry = new Person
{
Name = "Larry Nung",
NickName = "Larry"
};

Console.WriteLine (JSON. Serialize(larry ));
}

public class Person
{
[ JilDirective(false )]
public String Name { get; set ; }

[ JilDirective(true )]
public String NickName { get; set ; }
}
}
}


如果要客製輸出的 Element 名稱,則直接透過 JilDirectiveAttribute 帶入指定的名稱:

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
using System;
using System. Runtime.Serialization ;
using Jil;

namespace ConsoleApplication10
{
class Program
{
static void Main( string[] args )
{
var larry = new Person
{
Name = "Larry Nung",
NickName = "Larry"
};

Console.WriteLine (JSON. Serialize(larry ));
}

public class Person
{
[ JilDirective("name" )]
public String Name { get; set ; }

[ JilDirective(true )]
public String NickName { get; set ; }
}
}
}