0

I have read a few posts here and on GitHub regarding .NET Core 3.1's change in tightening of the allowance of serializing data. My actual exception is:

System.Text.Json.JsonException: 'A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 0.'

When I search the web, there are very few results, but from what I gather, it's telling me that it doesn't like the related data that is being serialized. Well, in the past, this hasn't been a problem. After reading this post, it says to install the Newtonsoft Json serializer package. I did that, and added the verbiage in Startup, but got the same result. So, I read another post here where the member who answered the question returned a JsonResult in the method. I tried this as a test and it worked just fine. Problem is, I need to return the data (serialized) to a view.

My question is, why can the standard System.Text.Json.JsonSerializer not serialize my data, yet a JsonResult can? Either way, I just need to serialize my data and cannot get past this error and any help would be greatly appreciated. If I have to return the data via an API and continue to use the JsonResult, I'm fine with that, but am concerned as to why it works.

clockwiseq
  • 4,189
  • 9
  • 38
  • 61
  • If you want the serialized JSON in the view, then pass the actual data object to the view and then use `@Json.Serialize(data)` inside the view. That will use the same serializer settings as `JsonResult`. – poke Jan 24 '20 at 09:17

1 Answers1

1

As @poke suggested, using Json.Serialize works. I was using System.Text.Json.JsonSerializer.Serialize(Model) and for some strange reason, this throws the same exception even though the Ignore option is set in Startup. More research is required, but at least this gives me something to look into.

clockwiseq
  • 4,189
  • 9
  • 38
  • 61
  • 1
    As I said, `Json.Serialize` in a model uses the same serializer settings as you have configured for the whole application. E.g. if you enabled Newtonsoft.Json, then that will be used there. If you just call `JsonSerializer.Serialize`, then you are circumventing any configuration and just serializing without any serializer settings. – poke Jan 24 '20 at 20:22
  • That's fantastic information to know. Do you have any link on the Microsoft site that explains that by any chance? – clockwiseq Jan 25 '20 at 15:47
  • No, I don't have a link for that. – poke Jan 25 '20 at 17:16