Read-only model property, not serialized in the web API

According to the title, I see that my read-only model properties are not serialized in my web API project. MVC 4 Web API, VS2010.

I saw a lot of posts, such as https://stackoverflow.com/a/168269/16732 , which states that the MVC 4 Web API beta strong> does not support read-only JSON serialization. But many sitelinks stated that the latest release uses JSON.NET instead of DataContractJsonSerializer, so the problem should be resolved.

Is this issue fixed or not? If not, am I forced to put fake setters to get serialization?


The correction it does seems to work with JSON (sorry!), But XML demonstrates this problem. Same question as before, but in the context of XML serialization.

+6
source share
1 answer

By default, the JSON serializer is now Json.NET. Thus, serializing readonly properties should work without having to do anything at all.

For XML in 4.5, we added this flag to the DataContractSerializer:

http://msdn.microsoft.com/en-us/library/vstudio/system.runtime.serialization.datacontractserializersettings.serializereadonlytypes.aspx

You should write something like this:

config.Formatters.XmlFormatter.SetSerializer(myType, new DataContractSerializer(myType, new DataContractSerializerSettings() { SerializeReadOnlyTypes = true }); 

Put this code in a function called GlobalConfiguration.Configure in Application_Start . By default, this will be WebApiConfig.Register() .

+7
source

All Articles