Search code examples
.netasp.net-mvcjsonjsonserializer

Rename field in JsonSerializer


I have a class library that I need to output via a JsonResult in the ASP.NET MVC framework. (JsonResult uses the JsonSerializer to produce its output.)

I discovered through reading the documentation that if you put [ScriptIgnore] on a public property/field, it will not get serialized, much like [XmlIgnore] for the XML serializer.

I need the equivalent functionality of [XmlElement("elementname")], which specifies absolutely the name of the field/property in the output serialization. I have a field called Elements that needs to get serialized to a field named elements.

How can I accomplish this using the default JsonSerializer?

Thanks, David


Solution

  • Are you using the DataContractJsonSerializer class?

    If so ...

    Add this attribute to you Elements field

    [DataMember(Name = "elements")] 
    

    This SO question suggests how to override the use of JsonScriptSerializer to JsonDataContractSerializer.

    Kindness,

    Dan