问题
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.
回答1:
Short Answer: Make sure all your assemblies are referencing the SAME EXACT JSON.NET DLL. What's probably happening is you are applying [JsonProperty]
from one DLL in one assembly, and serializing the object from a different assembly which is looking for a different [JsonProperty]
and because the CLR object types are different it is effectively being ignored.
Longer Answer: I just had this problem but fortunately because I had one class that was working with JsonProperty
and one that wasn't I was able to do some detective work.
I stripped the non-working class down to the bare minimum and compared it to the working class and couldn't see ANY differences - except for the fact that the non-working class was in a different assembly.
When I moved the class to the other assembly it worked perfectly as it should.
I poked around for a bit trying to look into JSON serialization of namespaces, but that didn't seem to apply so I looked at the references and sure enough I was referencing an old JSONNET3.5 DLL in my entities DLL and the NUGET 4.5 version in my main project file.
This gives me two instances of [JsonProperty]
attribute (which is just a regular class) and just because they're named the same doesn't mean the serializer is going to even recognise the attribute.
回答2:
This post helped me.
I used serialiser:
new JavaScriptSerializer().Serialize(message)
But rigtly use this:
JsonConvert.SerializeObject(message);
回答3:
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...
来源:https://stackoverflow.com/questions/8424151/json-net-serializer-ignoring-jsonproperty