mongodb 序列化Mongo ObjectId时发生JSON.NET转换错误

avkwfej4  于 2023-02-21  发布在  Go
关注(0)|答案(7)|浏览(267)

我正在玩MongoDB,有一个对象上面有一个mongodb ObjectId,当我用.NET Json()方法序列化这个对象时,一切都很好(但是日期太可怕了!)
如果我用JSON .NET序列化器尝试这个,当我尝试序列化ObjectID时,它会给我一个InvalidCastException
有什么想法发生了什么事,我怎么能解决这个问题?

using MongoDB.Driver;
using MongoDB.Bson;
using Newtonsoft.Json;

//this is a route on a controller
   public string NiceJsonPlease()
    {

        var q = new TestClass();
        q.id = new ObjectId();
        q.test = "just updating this";

        return JsonConvert.SerializeObject(q);
    }

    //simple test class
    class TestClass
    {
        public ObjectId id; //MongoDB ObjectID
        public string test = "hi there";
    }

Exception Details: System.InvalidCastException: Specified cast is not valid.

如果您将控制器方法更改为使用.NET附带的序列化程序,它可以正常工作(但是,这个方法给出了难看的日期,blugh)

public JsonResult NiceJsonPlease()
    {

        var q = new TestClass();
        q.id = new ObjectId();
        q.test = "just updating this";

        return Json(q, JsonRequestBehavior.AllowGet);
    }
7eumitmz

7eumitmz1#

你可以使用.NET字符串类型来代替ObjectId,你只需要用BsonRepresentation来修饰它。如果你使用BsonDateTime,你将有同样的转换问题。这是我的项目中的一个域类,它使用了那些装饰器。

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

    [BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
    public DateTime DownloadTime { get; set; }
}
8ftvxx2r

8ftvxx2r2#

我有一个来自MongoDB用户组的指针。https://groups.google.com/forum/?fromgroups =#!主题/mongodb-csharp/A_DXHuPscnQ
回答是
这似乎是Json .NET的问题,但实际上不是。这里有一个它根本不知道的自定义类型。您需要告诉Json .NET如何序列化ObjectId。
因此,我实现了以下解决方案
我用

[JsonConverter(typeof(ObjectIdConverter))]

然后编写了一个自定义转换器,它只输出ObjectId的Guid部分

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);
        //return true;
    }

}
yquaqz18

yquaqz183#

1.写入ObjectId转换器
公共类对象标识转换器:公共重写bool可以转换(类型对象类型){返回对象类型==类型(对象ID);}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
 {
     if (reader.TokenType != JsonToken.String)
         throw new Exception($"Unexpected token parsing ObjectId. Expected String, got {reader.TokenType}.");

     var value = (string)reader.Value;
     return string.IsNullOrEmpty(value) ? ObjectId.Empty : new ObjectId(value);
 }

 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
 {
     if (value is ObjectId)
     {
         var objectId = (ObjectId)value;
         writer.WriteValue(objectId != ObjectId.Empty ? objectId.ToString() : string.Empty);
     }
     else
     {
         throw new Exception("Expected ObjectId value.");
     }
 }

}
1.使用全局设置在JSON.NET中全局注册它,并且不需要用大属性标记模型

var _serializerSettings = new JsonSerializerSettings()
         {
             Converters = new List<JsonConverter> { new ObjectIdConverter() }
         };

1.重要建议-不要在模型中使用ObjectId-使用字符串
[BsonRepresentation(BsonType.ObjectId)]公共字符串Id {get;设置;}

4xrmg8kj

4xrmg8kj4#

我通过将JsonOutputMode设置为strict解决了JSON.NET序列化程序/InvalidCastException错误中遇到的类似问题,这消除了更改底层类型的需要:

var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict };
var json = doc.ToJson(jsonWriterSettings);

API中提供了更多信息:http://api.mongodb.org/csharp/1.8.3/html/d73bf108-d68c-e472-81af-36ac29ea08da.htm

mznpcxlj

mznpcxlj5#

我在一个WebAPI项目中遇到了类似的问题,在找到这个线程之前,我的头在键盘上敲打了几个小时。
最初一切正常,但在将代码转换为使用自己的自定义类而不是mongoDB C#驱动程序文档中推荐的BsonDocument对象后,我遇到了这个问题。
http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-csharp-driver/#bsondocument-object-model-vs-your-own-domain-classes
这里的VB.net等同于上面的解决方案,为那些需要它;

Public Class DocumentMetadata
    <BsonId> _
    <BsonRepresentation(BsonType.ObjectId)> _
    Public Property Id() As String
    Public Property Name() As String
    Public Property FullName() As String

    <BsonDateTimeOptions(Kind := DateTimeKind.Utc)> _
    Public Property DownloadTime() As DateTime
End Class
hrirmatl

hrirmatl6#

还有另一个选择

object dotnetObject = BsonTypeMapper.MapToDotNetValue(bsonDocument);

// Json mapped to default .Net objects
string json = Newtonsoft.Json.JsonConvert.SerializeObject(dotnetObject);

// Parsing as JObject
var jobject = JObject.Parse(json);

// Deserializing as your custom Type
var myObject = JsonConvert.DeserializeObject<MyType>(json);
fzsnzjdm

fzsnzjdm7#

我在VB.NET中使用了这段代码,效果很好,你可以在类中看到objectId,你可以对数据类型DATE做同样的事情。

Imports MongoDB.Bson
    Imports MongoDB.Bson.Serialization.Attributes    
    Imports MongoDB.Driver

Public Class _default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim objMongo As New MongoClient("mongodb://192.168.111.5:27017")
        Dim objDatabase As IMongoDatabase = objMongo.GetDatabase("local")
        Dim objCollection = objDatabase.GetCollection(Of BsonDocument)("Test")            
        Dim _ret As New List(Of mongo_users)

        Dim result = objCollection.Find(New BsonDocument()).ToList()
        Dim _json_response = result.ToJson()
        If _json_response <> "" Then

            _ret = MongoDB.Bson.Serialization.BsonSerializer.Deserialize(Of List(Of mongo_users))(_json_response)

        End If

        For Each item In _ret
            Response.Write(item.name & " " & item.last_name & "</br>")
        Next

    End Sub

End Class

Public Class mongo_users            
    <BsonId>
    <BsonRepresentation(BsonType.ObjectId)>
    Public Property _id() As String
    Public Property status As Integer
    Public Property name As String
    Public Property last_name As String
    Public Property colors As List(Of user_colors)    
End Class

Public Class user_colors
    Public Property color_name As String
End Class

相关问题