Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Json object with "multi-type" property

I'm following the Create a web API with ASP.NET Core and MongoDB Tutorial

And I'm missing something very basic, how to serialize a Json object that has a property that could be "multi-type". That is, this property could be a string, or another object.

This is the original Json sample in the tutorial:

{
  "_id" : ObjectId("5bfd996f7b8e48dc15ff215d"),
  "Name" : "Design Patterns",
  "Author" : "Ralph Johnson"
}

This is the original POCO Model in the tutorial:

public class Book
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [BsonElement("Name")]
    public string BookName { get; set; }
    public string Author { get; set; }
}

When I call the "Post" and "Get" action on the WebApi Controller, the original Json model is serialized correctly into an instance of Book, saved into the database and retrieved correctly from the web service as expected.

But, I need to add a "MultiUse" property, where MultiUse could either be a string or an object, or something else, for example:

{
 "_id" : ObjectId("5bfd996f7b8e48dc15ff215d"),
 "Name" : "Design Patterns",
 "Author" : "Ralph Johnson",
 "MultiUse": "Some String"
}

or

{
 "_id" : ObjectId("5bfd996f7b8e48dc15ff215d"),
 "Name" : "Design Patterns",
 "Author" : "Ralph Johnson",
 "MultiUse": {
     "foo":"bar"
  }
}

If I try to Post an object, this MultiUse property is serialized as another .Net type.

enter image description here

What type should MultiUse be in the POCO Model? I've tried Object, Dynamic, BsonDocument, but it is clear I think that AspNet and MongoDb driver will not automatically serialize it as I need it.

This multi-value property is pretty much the only reason I want to use MongoDB, I just want to save whatever is in that property into the database.

This situation works without problems in ExpressJS, but I need .Net because of client requirements.

Of course, I can just drop the strongly typed schema and use the MongoDB net driver functions to insert, update and query without the models. But since this "should" be a common scenario I just wanted to know how is this being handled.

like image 757
The One Avatar asked Jun 12 '21 03:06

The One


1 Answers

There are several ways to solve this problem, my suggestion is to import Newtonsoft.Json, then use MultiUse as JObject, or if MultiUse is array as Jarray.

like image 130
DvirB Avatar answered Sep 30 '22 17:09

DvirB