views:

247

answers:

1

Is there an equivalent Attribute that can be placed on object Properties in a .NET Class that would perform the equivalent of XmlElement or XmlAttribute?

[XmlRoot("objects")]
public class MyObjects: List<MyObject> { }

[XmlRoot("object")]
public class MyObject {
  [XmlAttribute("name")]
  public string Name { get; set; }
  [XmlAttribute("title")]
  public string Title { get; set; }
}

This would return XML similar to the following:

<objects>
  <object name="David" title="Engineer" />
  <object name="William" title="Developer" />
</objects>

I would like to have the JavaScriptSerializer, used by the ASP.NET MVC Frameworks 'Json' method in the Controller class:

public ActionResult Search() {
   // code to populate data object
   return Json(data);
}

Return the same formatted results, like so:

[{"name":"David","title":"Engineer"},{"name":"William","title":"Developer"}]

Currently, outputting the object with the Json method, returns:

[{"Name":"David"}, "Title":"Engineer"}, {"Name":"William", "Title":"Developer"}]

Now, I realize this example is super simplified and the only thing I've done here is change the casing of the property names but in more advanced scenarios I may completely remap the property name to something else ...

System.Web.Script.Serialization contains a ScriptIgnoreAttribute attribute, but this simply tells the JavaScriptSerializer to ignore the property when serializing, nothing appears to exist to change the names or format of the actual output however?

A: 

With JavaScript serializer (.NET 2.0), not really...
With DataContractSerializer (.NET 4.0,), yes.


See http://stackoverflow.com/questions/1100191/javascriptserializer-deserialize-how-to-change-field-names
for all the alternatives you have.

Quandary