JSON.Net serializer ignoring JsonProperty?

I had the same problem (.Net Core 3.1) and the reason was that I was using JsonPropertyName annotation, which is in System.Text.Json.dll but using JsonConvert.Serialize(string), which is obviously in Newtonsoft.Json.dll. It seems the serialization functions only respect their own library annotations. Changing JsonPropertyName annoation to JsonProperty fixed it, as the latter is in Newtonsoft.Json.dll


In my case I was applying the JsonProperty atrtibute on properties alright, but since I was using asp.net core 3.1, types from System.Text.Json were used, not types from JSON.Net. So if you start using asp.core 3.1, you should make a decision as to which library you would like to use for json. HTH.


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.


This post helped me.

I used serialiser:

new JavaScriptSerializer().Serialize(message)

But rigtly use this:

JsonConvert.SerializeObject(message);

Tags:

C#

Json

Json.Net