The DataContractJsonSerializer
uses opt-in semantics, which means that you must mark the class(es) to be serialized with a [DataContract]
attribute, and mark all members of those classes that you want serialized with [DataMember]
. If you cannot change the classes (because they are precompiled or you don't otherwise control the source code), then there's not much you can do with this serializer short of copying the data into another class that can be serialized. But, with ASP.NET MVC you shouldn't really be using DataContractJsonSerializer
anyway-- this serializer was created for WCF and is not very flexible or user-friendly, IMO.
The ASP.NET MVC framework has a Json
method built into the base controller, which uses the JavaScriptSerializer
behind the scenes to serialize your model objects. This serializer does not require marking up classes with attributes, and because it is baked-in you don't have to put any special serialization code into your controller methods to use it. Just change your method to return JsonResult
instead of ActionResult
, then pass your object to the Json
method as a last order of business.
For example:
[HttpGet]
public JsonResult GetItem(int id)
{
PrecompiledClass pc = RetrieveObjectFromDatabaseOrWhatever(id);
return Json(pc, JsonRequestBehavior.AllowGet);
}
The JavaScriptSerializer
does have some limitations that I won't go into here, which you probably won't hit in most normal circumstances. But if you do find that the JavaScriptSerializer
does not suit your needs, you can switch to a robust third-party serializer like Json.Net. See ASP.NET MVC and Json.NET and Using JSON.NET as the default JSON serializer in ASP.NET MVC - is it possible? to learn more about that option.