JSON.Net serializer ignoring JsonProperty?

旧街凉风 提交于 2019-12-04 22:30:00
Simon_Weaver

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.

user5866334

This post helped me.

I used serialiser:

new JavaScriptSerializer().Serialize(message)

But rigtly use this:

JsonConvert.SerializeObject(message);

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...

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!