2013-07-15 38 views
2

我使用MongoDB數據庫和MVC4 WebAPI,使用MongoDB提供的C#驅動程序。我有一個序列化問題。我收到以下錯誤:MongoDB C#驅動程序和MVC4 webapi。在json序列化中的問題

"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

+0

你能分享一下你試圖序列化成JSON的類型嗎?另外,從它說'MongoDB.Bson.ObjectId'的錯誤,它應該是Bson格式化器嗎?菲利普有一個創建BSON格式化器的例子:https://gist.github.com/filipw/3160050 –

+0

你能分享你的模型嗎 –

+0

我已經複製了上面的模型。問題是ObjectId沒有被序列化。謝謝 – user1615476

回答

1

對於任何試圖在提到 「解決方案」答案是:它根本行不通!

改爲在this中檢查標記的答案。

相關問題