20

I am currently working with ASP.NET web api where I return a Model object like following from my REST operation:

Product with properties: Name, Id, Description, etc.....

When this is converted to a JSON object, it outputs it with property names above.

To cut down the payload returned from the web api operation, is there any way I can change the properties in the JSON object like for example Desc for Description. I could change the Model object but the property names would not make sense then!

Prashanth Thurairatnam
  • 4,353
  • 2
  • 14
  • 17
amateur
  • 43,371
  • 65
  • 192
  • 320

2 Answers2

25

The easy way to do this is through a data contract. Here is an article, but basically, it involves two annotations on your model. It also allows you to ignore anything you don't want serialized.

[DataContract]
public class Foo {  //Your model class

   [DataMember(Name="bar-none")]  //This also allows you to use chars like '-'
   public string bar {get; set;}

   [IgnoreDataMember]  //Don't serialize this one
   public List<string> fuzz { get; set;}

}
AdamC
  • 16,087
  • 8
  • 51
  • 67
  • 1
    This was perfect for my purposes, which were the same as OP's. – ThisGuyKnowsCode May 22 '13 at 12:27
  • 4
    You might also need to add a reference to System.Runtime.Serialization which isn't added by default. http://stackoverflow.com/questions/7401795/namespace-for-datacontract – geon Oct 07 '13 at 14:03
1

You could also consider using http://automapper.org/ on the asp.net side to map your full objects, to more lightweight ones. Might be overkill for just one or two small objects, but if you have a bunch to do this can save you some time (free and open source to boot).

E.J. Brennan
  • 45,870
  • 7
  • 88
  • 116