使用具有对象拥有ID的newtonsoft Json保留对象引用

时间:2015-12-29 08:01:10

标签: json json.net

我正在和newtonoft Json一起学习Preserving Object References。 当我运行以下代码时,

class Person
{
    public DateTime BirthDate { get; set; }

    public DateTime LastModified { get; set; }

    public string Name { get; set; }

    public int Id { get; set; }
}

class Program
{
    static int m_Counter = 20;
    static void Main(string[] args)
    {
        Person p1 = new Person
        {
            Id = m_Counter++,
            BirthDate = new DateTime(1980, 12, 23, 0, 0, 0, DateTimeKind.Utc),
            LastModified = new DateTime(2009, 2, 20, 12, 59, 21, DateTimeKind.Utc),
            Name = "James"
        };

        Person p2 = new Person
        {
            Id = m_Counter++,
            BirthDate = new DateTime(1980, 12, 23, 0, 0, 0, DateTimeKind.Utc),
            LastModified = new DateTime(2009, 2, 20, 12, 59, 21, DateTimeKind.Utc),
            Name = "James"
        };

        List<Person> people = new List<Person>();
        people.Add(p1);
        people.Add(p1); // Adding the same person twice.

        string json = JsonConvert.SerializeObject(people, Formatting.Indented
            , new JsonSerializerSettings
            {
                PreserveReferencesHandling
                    = PreserveReferencesHandling.Objects
            }
            );
        Console.WriteLine(json);
        Console.ReadLine();
    }
}

我得到以下JSON

[
  {
    "$id": "1",
    "BirthDate": "1980-12-23T00:00:00Z",
    "LastModified": "2009-02-20T12:59:21Z",
    "Name": "James",
    "Id": 20
  },
  {
    "$ref": "1"
  }
]

在这里,我看到Newtonsoft正在为每个对象创建自己的id。 所以我想知道是否有任何方法可以指示Newtonsoft使用对象本身的Id(本例中为20)而不是创建自己的(“$ id”:“1”)

0 个答案:

没有答案