Abc.net Core To Json serialization configuration, abpjson
I. Preface
The attribute names obtained after ToJson serialization of the front-end results returned by using the abcarchitecture MVC Controller or Web API are all in the js camper format, that is, the first letter is lowercase, the format in which the first letter of a word is capitalized (for example, the backend attribute name is OrderName, and the returned frontend js name is orderName ). However, in actual project development, for some reason (such as providing interfaces to the old system or integrating the existing system), the backend attribute names must be consistent or in a specific format, next we will introduce how to modify the default configuration and custom configuration based on the ABC architecture ToJson.
Ii. Modify the default ToJson serialization Configuration
Modify the default configuration in the Startup file. The Code is as follows:
Public class Startup {private readonly IConfigurationRoot _ appConfiguration;
Public Startup (IHostingEnvironment env) {_ appConfiguration = env. GetAppConfiguration ();} public IServiceProvider ConfigureServices (IServiceCollection services) {// MVC services. AddMvc ()
. AddJsonOptions (options =>{ // configure DefaultContractResolver in tojson format to be consistent with the background attribute name (that is, the background attribute name is OrderName, And the frontend js obtains the attribute name is also OrderName) options. serializerSettings. contractResolver = new DefaultContractResolver (); // modify it to CamelCasePropertyNamesContractResolver, which is the default format of JavaScript CamelCasePropertyNamesContractResolver (that is, the backend attribute name is OrderName and the front) // options. serializerSettings. contractResolver = new CamelCasePropertyNamesContractResolver ();});}}
3. Custom ToJson serialization Configuration
To customize the ToJson serialization format, write a subclass to inherit defaconcontractresolver and override the ResolvePropertyName method. The Code is as follows:
Public class MyPropertyNamesContractResolver: DefaultContractResolver {protected override string ResolvePropertyName (string propertyName) {// All attribute names return lower case properreturn tyname. ToLower ();}}
Next, replace the configuration with MyPropertyNamesContractResolver in the Startup file.
Services. AddMvc ()
. AddJsonOptions (options =>{ // Replace the tojson format with the custom format MyPropertyNamesContractResolver (that is, the backend attribute name is OrderName, And the frontend js obtains the attribute name ordername) options. serializerSettings. contractResolver = new MyPropertyNamesContractResolver ();});