Serialize one to many relationships in Json.net

后端 未结 5 562
盖世英雄少女心
盖世英雄少女心 2020-12-08 08:44

I am using the Entity Framework code first for data access and I have a Company class which has a collection of Employees. The Employee class also has a Company property.

5条回答
  •  长情又很酷
    2020-12-08 09:05

    I think they have fixed this in the latest version.

    Check out the help docs under the section "Serializing and Deserializing JSON -> Serialization and Preserving Object References".

    Set this setting when initializing the JSON.Net Serializer:

    PreserveReferencesHandling = PreserveReferencesHandling.Objects;
    

    So an example would be this:

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

    I verified that this works with my code first solution, and a circular reference in the navigation properties. If you look at the resulting JSON it should have "$id" and "$ref" properties everywhere.

提交回复
热议问题