How to have JSON.NET render forward references during serialization

笑着哭i 提交于 2019-12-12 03:22:13

问题


JSON.NET (using the setting PreserveReferencesHandling = PreserveReferencesHandling.Objects) serializes a reoccurring object inline on first occurrence and serialzes it as JSON reference on subsequent occurrences. I'm guessing this is done to avoid forward references.

For example:

class Person
{
    public string Name { get; set; }
    public Person Mother { get; set; }
}

var joni = new Person { Name = "Joni" };
var james = new Person { Name = "James", Mother = joni };

var people = new List<Person> { james, joni };

var json = JsonConvert.SerializeObject(people, Formatting.Indented,
    new JsonSerializerSettings {
       PreserveReferencesHandling = PreserveReferencesHandling.Objects });

results in the following:

[
  {
    "$id": "1",
    "Name": "James",
    "Mother": {
      "$id": "2",
      "Name": "Joni",
      "Mother": null
    }
  },
  {
    "$ref": "2"
  }
]

Instead, I'd like to get this:

[
  {
    "$id": "1",
    "Name": "James",
    "Mother": {
      "$ref": "2"
    }
  },
  {
    "$id": "2",
    "Name": "Joni",
    "Mother": null    
  }
]

Although both are effectively equal, I find the second much more sensible, especially when editing the JSON data by hand (which is a use case for me in this matter).

Is there a way of controlling which instance is serialized as a reference or am I stuck with this first-occurrence behavior?

EDIT

I've tried deserializing the desired JSON and found that JSON.NET doesn't do that properly because of the forward reference.


回答1:


What is going on there is that you are instancing a Person variable inside your Person variable. So when you create the "son":

class Person
{
    public string Name { get; set; }
    public Person Mother { get; set; }
}

You are creating a Mother variable inside, that is a Person type variable, and has all the attributes that a regular Person variable would have, with the resulting JSON file you are obtaining.

Instead of doing that, you can try to create a new class "Mother" that inherits from the class "Person" and only has the ID attribute, so when you create the JSON file, you will obtain the expected result.



来源:https://stackoverflow.com/questions/34675949/how-to-have-json-net-render-forward-references-during-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!