序列化对象

自定义对象

使用 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
26
27
using System;
using Newtonsoft.Json;


namespace ConsoleApp3
{
    class Person
    {
        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("age")]
        public int? Age { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.Name = "张三";
            p.Age = 20;
            Console.WriteLine(JsonConvert.SerializeObject(p, Formatting.None, new JsonSerializerSettings));
        }
    }
}

输出结果如下:

1
{"name":"张三","age":20}

如果 Age 没有赋值,默认为 null, 会被序列化成 null

1
2
3
Person p = new Person();
p.Name = "张三";
Console.WriteLine(JsonConvert.SerializeObject(p));
1
{"name":"张三","age":null}

可以设置不要序列化值为 null 的成员,有两种方式,第一种:

1
2
3
4
5
6
Person p = new Person();
p.Name = "张三";
Console.WriteLine(JsonConvert.SerializeObject(
                      p,
                      Formatting.None,
                      new JsonSerializerSettings{ NullValueHandling = NullValueHandling.Ignore }));

或者在 JsonProperty 里声明:

1
2
3
4
5
6
7
8
class Person
{
    [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
    public string Name { get; set; }

    [JsonProperty("age", NullValueHandling=NullValueHandling.Ignore)]
    public int? Age { get; set; }
}

输出结果如下:

1
{"name":"张三"}

不要序列化成员,但是要反序列化

通过实现 ShouldSerializePropertyName 实现,如:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Person
{
    [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
    public string Name { get; set; }

    [JsonProperty("age", NullValueHandling=NullValueHandling.Ignore)]
    public int? Age { get; set; }

    [JsonProperty("available", NullValueHandling = NullValueHandling.Ignore)]
    public bool Available { get; set; } = false;

    public bool ShouldSerializeAvailable()
    {
        return false;
    }
}