0

I have controller method Task<IActionResult> AddAsync([FromBody] DocumentPostDTO documentDto) and dto:

public class DocumentPostDTO
{
    public string Path { get; set; }
    public dynamic? Content { get; set; }
}

Content here is a dynamic JSON that can be anything. Here are some payload examples:

{
  "path": "/Hey/abc",
  "content": {
    "string": ")asgadfsghaspgo"
  }
}
{
  "path": "/Samples/1ZCTNoQduq8TXgD-",
  "content": {
    "string": ")XYjU)RxfMVd&34xi8M!",
    "obj": {
      "int": 1
    }
  }
}

So, when I get this Content property I want to assign it to plain object and save in MongoDb.

object _content = documentDto.Content;

But what I am actually getting in object is some kind of weird System.Text.Json.JsonValueKind object which doesn't contain the properties passed. Result in db:

"Content": {
  "_t": "System.Text.Json.JsonValueKind, System.Text.Json, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51",
  "_v": 1
}
Deivydas Voroneckis
  • 1,973
  • 3
  • 19
  • 40
  • Please show your code as a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example), especially including the controller code – Ermiya Eskandary Nov 02 '21 at 09:03
  • Yes, that's correct. Your `dynamic Content` is deserialized as a [`JsonElement`](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonelement) by System.Text.Json, which is the new JSON serializer in .NET core 3.x and onward. So what are your options? 1) If you don't like that you could switch back to Json.NET. To do that see [Where did IMvcBuilder AddJsonOptions go in .Net Core 3.0?](https://stackoverflow.com/q/55666826/3744182)... – dbc Nov 02 '21 at 17:33
  • ... 2) You could work directly with `JsonElement` as shown in [Read value from dynamic property from json payload](https://stackoverflow.com/a/64036531/3744182). 3) You could write a custom [`JsonConverter`](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to) to deserialize the freeform JSON content to an `ExpandoObject` as shown in [C# - Deserializing nested json to nested Dictionary](https://stackoverflow.com/a/65974452/3744182). – dbc Nov 02 '21 at 17:33
  • Do either or all of those three questions answer yours sufficiently? If not, what more specific help do you need? – dbc Nov 02 '21 at 17:40
  • The reason of this behavior that the driver should know what type he needs to use during deserialization. For that the driver use discriminator logic https://mongodb.github.io/mongo-csharp-driver/2.14/reference/bson/mapping/ – dododo Nov 29 '21 at 17:32
  • Thank you for your replies. The problem was that my app was using the default `System.Text.Json`. After switching to `Newtonsoft.Json` I changed `dynamic` to `Dynamic` and it deserializes nicely. – Deivydas Voroneckis Nov 29 '21 at 19:16

0 Answers0