Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlAttribute/XmlElement equivalent for JavaScriptSerializer

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?

like image 568
David Higgins Avatar asked Sep 24 '09 14:09

David Higgins


1 Answers

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


See
JavaScriptSerializer.Deserialize - how to change field names
for all the alternatives you have.

When you're ready to realize that the built-in serializer is not really useful, use JSON.NET, add a reference to Newtonsoft.JSON, and do it like this:

[JsonProperty(PropertyName = "FooBar")]
public string Foo { get; set; }
like image 145
Stefan Steiger Avatar answered Oct 23 '22 10:10

Stefan Steiger