受欢迎的博客标签

This blog describer How MongoDb ObjectID JSON String Format in Asp .NET Core。

Add JsonObjectIdConverter convert ObjectId to string,otherwise it is “00000000000000000000000000”

with Nopcommerce admin web Problem I have a collection of dynamic data. I want to get it back like this:

{ _id: "58b454f20960a1788ef48ebb" ... }

Attempts Here are a list of approaches that do not work:

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

return Ok(resources);

Yields [[{"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"}}}]]

Step one:Write a JsonObjectIdConverter,it will convert ObjectId to string when object field type is ObjectId

using MongoDB.Bson;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;

namespace Nop.Web.Framework.Json
{

    /// <summary>
    /// question and answer:https://www.cpume.com/question/ffzgitse-mongo-c-sharp-driver-and-objectid-json-string-format-in-net-core.html
    /// soucecode come from :https://gist.github.com/cleydson/d1583f87f6fb7e2a8ee67e2455a1bb56
    /// </summary>
    public class JsonObjectIdConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value.GetType().IsArray)
            {
                writer.WriteStartArray();
                foreach (var item in (Array)value)
                {
                    serializer.Serialize(writer, item);
                }
                writer.WriteEndArray();
            }
            else
                serializer.Serialize(writer, value.ToString());
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var token = JToken.Load(reader);
            var objectIds = new List<ObjectId>();

            if (token.Type == JTokenType.Array)
            {
                foreach (var item in token.ToObject<string[]>())
                {
                    objectIds.Add(new ObjectId(item));
                }
                return objectIds.ToArray();
            }

            if (token.ToObject<string>().Equals("MongoDB.Bson.ObjectId[]"))
            {
                return objectIds.ToArray();
            }
            else
                return new ObjectId(token.ToObject<string>());
        }

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

 

Regex for MongoDB ObjectID

var myregexp = /^[0-9a-fA-F]{24}$/;
subject = "112345679065574883030833";

if (subject.match(myregexp)) {
    // Successful match
} else {
    // Match attempt failed
}

 

Other:

https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.Formatters.Json/2.0.0 https://www.nuget.org/packages/Microsoft.AspNetCore.JsonPatch/2.0.0  .