2

I am using MongoDB database with MVC4 WebAPI using the C# driver provided by MongoDB. I have a an issue with serialization. I get the following error,

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

If I change the Content-Type to xml in my HTTP request it just works fine. I would appreciate any help.

I have copied the model below.

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>();
}
}

Solution

Converting _id type string and decorating the field as below did the trick

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

reference: JSON.NET cast error when serializing Mongo ObjectId

Community
  • 1
  • 1
user1615476
  • 161
  • 2
  • 2
  • 7
  • Could you share how your type that you are trying to serialize into JSON looks like? Also, from the error it says `MongoDB.Bson.ObjectId`, is it supposed to be a Bson formatter instead? Filip has an example of creating a BSON formatter here: https://gist.github.com/filipw/3160050 – Kiran Jul 15 '13 at 15:44
  • could you share your model – Ajay Beniwal Jul 15 '13 at 16:56
  • I have copied the model above. The issue is that the ObjectId is not getting serialized. Thx – user1615476 Jul 16 '13 at 08:41

1 Answers1

1

For anyone trying the mentioned "solution" in the answer : It simply doesn't work!

Check the marked answer in this, instead.

Community
  • 1
  • 1
Illuminati
  • 4,539
  • 2
  • 35
  • 55