views:

153

answers:

2

Hi,

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

+2  A: 

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

Daniel Elliott
No, I am using the JsonSerializer. As I mentioned, it is required because it is what JsonResult uses in the MVC framework.
David Pfeffer
Added link to SO question explaining a route to use differenet (more configurable) Json serializer.
Daniel Elliott
Still not what I'm looking for, but this answers the question now and is really helpful. I might end up being forced down this road if no one can answer the question. Thanks!
David Pfeffer
+1  A: 

The unfortunate answer is, you cannot do it. Having said that, I am currently developing a module that will extend any object by producing at runtime an anonymous object that will follow rules from attributes, such as JsonIgnore or JsonProperty. I'll post more when I have something.

David Pfeffer