Search code examples
c#jsonjson.net

JSON.Net serializer ignoring JsonProperty?


I have the following entity class:

public class FacebookComment : BaseEntity
{
    [BsonId(IdGenerator = typeof(ObjectIdGenerator))]
    [BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
    [JsonProperty("_id")]
    public ObjectId Id { get; set; }

    public int? OriginalId { get; set; }
    public DateTime Date { get; set; }
    public string Message { get; set; }
    public string Sentiment { get; set; }
    public string Author { get; set; }
}

When this object is serialized to JSON, I want the Id field to be written as "_id":{...}. AFAIK, I should just have to pass the desired propertyname to the JsonProperty attribute; and I should be good to go. However, when I call JsonConvert.SerializeObject; it seems to ignore my attribute and renders this instead:

{
    Author: "Author name",
    Date: "/Date(1321419600000-0500)/",
    DateCreated: "/Date(1323294923176-0500)/",
    Id: {
        CreationTime: "/Date(0)/",
        Increment: 0,
        Machine: 0,
        Pid: 0,
        Timestamp: 0
    },
    Message: "i like stuff",
    OriginalId: null,
    Sentiment: "Positive"
}

As you can see, the Id field is being rendered with the wrong field name.

Any ideas? Been working on this issue for an hour; can't figure out why the serializer is seemingly ignoring my JsonProperty.

Any constructive input is greatly appreciated.


Solution

  • I fixed this issue by marking my Id property with [System.Runtime.Serialization.DataMember(Name="_id")] instead of JsonProperty. Still not entirely clear as to why it didn't work originally though...