【问题标题】:MongoDB C# driver and MVC4 webapi. Issue in json serializationMongoDB C# 驱动程序和 MVC4 webapi。 json序列化问题
【发布时间】:2013-07-15 14:37:06
【问题描述】:

我正在使用 MongoDB 数据库和 MVC4 WebAPI,使用 MongoDB 提供的 C# 驱动程序。我有一个序列化问题。我收到以下错误,

    "ExceptionMessage=Error getting value from '__emptyInstance' on 'MongoDB.Bson.ObjectId'"

如果我在我的 HTTP 请求中将 Content-Type 更改为 xml,它就可以正常工作。我将不胜感激。

我复制了下面的模型。

public class Subscriber
{
    public ObjectId _id;

    public long SubscriberId { get; set; }

    public Name Name { get; set; }

    public Address Address { get; set; }

    public string Phone { get; set; }

    public ICollection<Subscription> Subscription { get; set; }


    public Subscriber()
    {
        Name = new Name();
        Address = new Address();
        Subscription = new Collection<Subscription>();
}
}

解决方案

转换 _id 类型字符串并如下所示装饰字段

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string _id;

参考:JSON.NET cast error when serializing Mongo ObjectId

【问题讨论】:

  • 您能分享一下您尝试序列化为 JSON 的类型是什么样的吗?另外,从它说MongoDB.Bson.ObjectId的错误来看,它应该是Bson格式化程序吗? Filip 在这里有一个创建 BSON 格式化程序的示例:gist.github.com/filipw/3160050
  • 你能分享你的模型吗
  • 我复制了上面的模型。问题是 ObjectId 没有被序列化。谢谢

标签: asp.net-web-api mongodb-.net-driver


【解决方案1】:

对于任何尝试在答案中提到的“解决方案”的人:它根本行不通!

改为检查this 中的标记答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多