0

I'm trying to serialize some objects with Web API in JSON-format. However, the JSON Serializer doesn't respect the settings in Global.asax and keeps nesting objects too deep. I am using Web API in combination with Entity Framework Code First.

This is the JSON-related code in Global.asax:

var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;

jsonFormatter.SerializerSettings.ReferenceLoopHandling
            = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

jsonFormatter.SerializerSettings.PreserveReferencesHandling
            = Newtonsoft.Json.PreserveReferencesHandling.None;

I'm trying to get a list of Module-objects and this is the result: https://i.stack.imgur.com/yfh65.png

The content in the red shape is what I don't want to have serialized.

EDIT: Is it also possible to exclude specific properties and keep others?

Thanks in advance

Sn0wBlind
  • 123
  • 2
  • 10

1 Answers1

0

You have not provided the full model schema, but it seems that you don't need these settings in this case.

I suggest you to read accepted answer for this question which has a great explanation of how ReferenceLoopHandling and PreserveReferencesHandling settings are working. In general it's all about when you have the same object instance more than once in object tree that you want to serialize. Looking at your image it's not the case.

It seems that you are serializing your EF models and you are using lazy loading for connected objects. You might think of creating separate model for JSON serialization and populate only fields you need. Using this technique you will be sure what data is retrieved from DB.

Another option would be to use JsonIgnore attribute. You can mark needed properties in your EF models. For example:

public class A
{
    public string NameOfA { get; set; }

    [JsonIgnore]
    public string IgnoredProperty { get; set; }

    [JsonIgnore]
    public B B { get; set; }
}

public class B
{
    public string NameOfB { get; set; }
}

And if we execute this code:

var a = new A
{
    NameOfA = "A",
    IgnoredProperty = "Will be ignored",
    B = new B
    {
        NameOfB = "B"
    }
};
var json = JsonConvert.SerializeObject(a, Formatting.Indented);

The resulting JSON will be:

{
  "NameOfA": "A"
}
Community
  • 1
  • 1
Aleksandr Ivanov
  • 2,778
  • 5
  • 27
  • 35
  • Thanks for your answer! I decided to go with separate models which only contain the data I want to serialize. – Sn0wBlind Apr 06 '15 at 13:13