1

I want to serialize HttpListenerContext instance. But there are some mutable properties in this class, that cause side effects and JsonConverter just throw an error, when try to serialize an instance of this class.

What is the best solution for this problem? I see next ways to deal with it:

  1. Create custom wrapper class and list all necessary fields in it
  2. Write custom ContractResolver with tricky condition for serializable properties (for example: serialize only auto properties)

Can you suggest something? What is a general approach for this situation? How should I serialize mutable objects from external libraries?

For serialization, I use Newtonsoft.Json library and serialize object with JsonConverter.SerializeObject(...) method.

dbc
  • 104,963
  • 20
  • 228
  • 340
Nikita Sivukhin
  • 2,370
  • 3
  • 16
  • 33
  • I think this is very dependent on which library you are using. So please tell us which library you are using for serialization. Most libraries come with Attributes to handle this. – Sebi Mar 06 '17 at 06:26
  • @Sebi I use `Newtonsoft.Json` lib. But I can't mark `HttpListenerContext` class with some attributes, because this class from external lib. – Nikita Sivukhin Mar 06 '17 at 06:39
  • True story, then you will need a wrapper class. – Sebi Mar 06 '17 at 06:43
  • Why do you need to serialize this object? For logging? – Ygalbel Mar 06 '17 at 08:48
  • @Ygalbel Yes, I want to log incoming requests to server. – Nikita Sivukhin Mar 06 '17 at 08:49
  • 1
    You don't need to serialize it as JSON you can log http raw data, see [here](http://stackoverflow.com/questions/1038466/logging-raw-http-request-response-in-asp-net-mvc-iis7) – Ygalbel Mar 06 '17 at 08:54
  • 1) Do you only need to serialize `HttpListenerContext` or do you need to deserialize also? 2) You wrote, *`JsonConverter` just throw an error, when try to serialize an instance of this class.* What is the error? Can you share what you attempted so far as a [mcve]? – dbc Mar 06 '17 at 15:17

0 Answers0