Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override field name deserialization in ServiceStack

Tags:

I'm using ServiceStack to deserialize some HTML form values but can't figure out how to override the value that each field should be read from.

For example, the form posts a value to first_name but the property on my POCO is called FirstName. how would I do mapping like that in ServiceStack

like image 236
kay.one Avatar asked Apr 11 '12 21:04

kay.one


1 Answers

The ServiceStack Text serializers support [DataMember] aliases where you can use the Name parameter to specify what alias each field should be, e.g:

[DataContract] public class Customer {     [DataMember(Name="first_name")]     public string FirstName { get; set; }      [DataMember(Name="last_name")]     public string LastName { get; set; } } 

Note: Once you add [DataContract] / [DataMember] attributes to your DTOs then the behavior becomes opt-in and you will have add [DataMember] on each of the properties you want serialized.

Emitting idiomatic JSON for all DTOs

You can instruct JSON serialization to follow a different convention by specifying the following global settings:

//Emit {"firstName":"first","lastName":"last"} JsConfig.Init(new Config { TextCase = TextCase.CamelCase });  //Emit {"first_name":"first","last_name":"last"} JsConfig.Init(new Config { TextCase = TextCase.SnakeCase }); 
like image 147
mythz Avatar answered Sep 23 '22 05:09

mythz