Mongo C # Driver and ObjectID JSON String Format in .NET Core

Problem

I have a dynamic dataset. I want to return it like this:

{
  _id: "58b454f20960a1788ef48ebb"
  ... 
}

Attempts

Here is a list of approaches that do not work:

it

await resources = _database.GetCollection<BsonDocument>("resources")
    .Find(Builders<BsonDocument>.Filter.Empty)
    .ToListAsync();

return Ok(resources);

Productivity

[[{"name":"_id","value":{"bsonType":7,"timestamp":1488213234,"machine":614561,"pid":30862,"increment":16027323,"creationTime":"2017-02-27T16:33:54Z","rawValue":{"timestamp":1488213234,"machine":614561,"pid":30862,"increment":16027323,"creationTime":"2017-02-27T16:33:54Z"},"value":{"timestamp":1488213234,"machine":614561,"pid":30862,"increment":16027323,"creationTime":"2017-02-27T16:33:54Z"}}}]]

it

await resources = _database.GetCollection<BsonDocument>("resources")
    .Find(Builders<BsonDocument>.Filter.Empty)
    .ToListAsync();

return Ok(resources.ToJson());

Productivity

[{ "_id" : ObjectId("58b454f20960a1788ef48ebb"), ... }]

it

await resources = _database.GetCollection<BsonDocument>("resources")
    .Find(Builders<BsonDocument>.Filter.Empty)
    .ToListAsync();

return Ok(resources.ToJson(new JsonWriterSettings() { OutputMode = JsonOutputMode.Strict }));

Productivity

[{ "_id" : { "$oid" : "58b454f20960a1788ef48ebb" }, ... }]

it

await resources = _database.GetCollection<BsonDocument>("resources")
    .Find(Builders<BsonDocument>.Filter.Empty)
    .ToListAsync();

return Ok(Newtonsoft.Json.JsonConvert.SerializeObject(resources));

Productivity

"Newtonsoft.Json.JsonSerializationException: error retrieving value from" AsBoolean "in" MongoDB.Bson.BsonObjectId ". ---> System.InvalidCastException: cannot throw object of type 'MongoDB.Bson.BsonObjectId' to enter 'MongoDB.Bson.BsonBoolean ''

And changing BsonDocumentto dynamicgives the same results.

docs. , , ObjectId , - . , , .

_client = new MongoClient(clientSettings); 
_database = _client.GetDatabase(_settings.DatabaseName); 
BsonSerializer.RegisterSerializer(new ObjectIdSerializer());

...

class ObjectIdSerializer : SerializerBase<ObjectId>
{
    public override ObjectId Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        return context.Reader.ReadObjectId();
    }

    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, ObjectId value)
    {
        context.Writer.WriteString(value.ToString());
    }
}

.

+4
2

BsonDocument MongoDB

, , BsonDocument s.

public ActionResult Post([FromBody]JObject resource)
{
    var document = BsonDocument.Parse(resource.ToString(Formatting.None));

    DbContext.Resources.InsertOne(document);
}

BsonDocument JSON.Net

, ToJson() ISODate ObjectId , . , , . MongoDB.Bson.IO.JsonWriter class, BsonSerializer BsonValue :

MongoDB.Bson.BsonSerializationException: BsonObjectId, BsonValue.

, , , JSON.Net. MongoDB # Lead Robert Stam , Nathan .net-core.. , ObjectId ISODate.

NuGet . , .csproj :

<PackageReference Include="MongoDB.Integrations.JsonDotNet" Version="1.0.0" />

:

Startup.cs

using MongoDB.Integrations.JsonDotNet.Converters;

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().AddJsonOptions(options =>
        {
            // Adds automatic json parsing to BsonDocuments.
            options.SerializerSettings.Converters.Add(new BsonArrayConverter());
            options.SerializerSettings.Converters.Add(new BsonMinKeyConverter());
            options.SerializerSettings.Converters.Add(new BsonBinaryDataConverter());
            options.SerializerSettings.Converters.Add(new BsonNullConverter());
            options.SerializerSettings.Converters.Add(new BsonBooleanConverter());
            options.SerializerSettings.Converters.Add(new BsonObjectIdConverter());
            options.SerializerSettings.Converters.Add(new BsonDateTimeConverter());
            options.SerializerSettings.Converters.Add(new BsonRegularExpressionConverter());
            options.SerializerSettings.Converters.Add(new BsonDocumentConverter());
            options.SerializerSettings.Converters.Add(new BsonStringConverter());
            options.SerializerSettings.Converters.Add(new BsonDoubleConverter());
            options.SerializerSettings.Converters.Add(new BsonSymbolConverter());
            options.SerializerSettings.Converters.Add(new BsonInt32Converter());
            options.SerializerSettings.Converters.Add(new BsonTimestampConverter());
            options.SerializerSettings.Converters.Add(new BsonInt64Converter());
            options.SerializerSettings.Converters.Add(new BsonUndefinedConverter());
            options.SerializerSettings.Converters.Add(new BsonJavaScriptConverter());
            options.SerializerSettings.Converters.Add(new BsonValueConverter());
            options.SerializerSettings.Converters.Add(new BsonJavaScriptWithScopeConverter());
            options.SerializerSettings.Converters.Add(new BsonMaxKeyConverter());
            options.SerializerSettings.Converters.Add(new ObjectIdConverter());
        }); 
    }
}

:

return Created($"resource/{document["_id"].ToString()}", document);
+4

, ObjectIdConverter NewtonSoft.

await resources = _database.GetCollection<dynamic>("resources")
    .Find(Builders<dynamic>.Filter.Empty)
    .ToListAsync();

return Ok(Newtonsoft.Json.JsonConvert.SerializeObject(resources, new ObjectIdConverter()));

class ObjectIdConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value.ToString());

    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(ObjectId).IsAssignableFrom(objectType);
    }
}

. ObjectId String , BSONSerailzers bson ObjectId.

ObjectIds ObjectIdConverter .

: fooobar.com/questions/227267/...

+2

Source: https://habr.com/ru/post/1677604/


All Articles