title: System.Text.Json serialization against an anonymous object
body: <p>I'm working on an ASP .Net Core 3.1 application, porting part of the code from another using 2.2. So far, I'd like to switch from the NewtonSoft JSON serialization library to the new one, System.Text.Json, but I have some trouble.</p>
  
  <p>Consider a function to serve a HTTP-GET service with this returning type:</p>
  
  <pre><code>    [HttpGet("myservice")]
      public async Task&lt;ActionResult&lt;object&gt;&gt; GetDataAsync( ...
  </code></pre>
  
  <p>Then, the final part could be depicted as follows:</p>
  
  <pre><code>        var items = new List&lt;IMyInterface&gt;();
          int totalCount = ...
          int min = ...
          int max = ...
  
          return new ActionResult&lt;object&gt;(new
          {
              totalCount,
              min,
              max,
              items
          });
  </code></pre>
  
  <p>However, it doesn't work: the items collection is serialized by its declared type (IMyInterface), instead of the actual type(s). I read <a href="https://stackoverflow.com/questions/58429098/jsonserializer-behaves-not-as-expected-when-the-specifc-class-is-casted-to-somet">here</a> that this is an expected behavior, although not so intuitive to me.</p>
  
  <p>My question is: <strong>is there any convenient yet reliable way to leverage the new serializer even dealing with anonymous objects?</strong> I would avoid to create a specific object every time I can compose the result inline.</p>
  
  <p>UPDATE:</p>
  
  <p>doing this it seems to work, but it looks really ugly:</p>
  
  <pre><code>        return new ActionResult&lt;object&gt;(new
          {
              totalCount,
              min,
              max,
              items = items.Cast&lt;object&gt;()
          });
  </code></pre>