简体   繁体   中英

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.

在此处输入图像描述

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM