Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

managing property names returned in json from web api

Tags:

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!

like image 991
amateur Avatar asked May 23 '12 23:05

amateur


People also ask

What is Property name in JSON?

Objects are the mapping type in JSON. They map “keys” to “values”. In JSON, the “keys” must always be strings. Each of these pairs is conventionally referred to as a “property”.

Which line of code can you use to format JSON data in camel case?

If you want JsonSerializer class to use camel casing you can do the following: var options = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy. CamelCase }; string json = JsonSerializer. Serialize(empList, options); return Ok(json);


2 Answers

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;}

}
like image 86
AdamC Avatar answered Oct 21 '22 17:10

AdamC


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).

like image 34
E.J. Brennan Avatar answered Oct 21 '22 18:10

E.J. Brennan