Added UseCamelCasing and UseMemberCasing extension methods to MvcJsonOptions (#7256)

This commit is contained in:
Alexej Timonin 2018-06-22 20:31:00 +02:00 committed by Pranav K
parent 196e3f109f
commit 52c1e942c6
No known key found for this signature in database
GPG Key ID: 1963DA6D96C3057A
5 changed files with 542 additions and 0 deletions

View File

@ -0,0 +1,88 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Microsoft.Extensions.DependencyInjection
{
public static class MvcJsonOptionsExtensions
{
/// <summary>
/// Configures the casing behavior of JSON serialization to use camel case for property names,
/// and optionally for dynamic types and dictionary keys.
/// </summary>
/// <remarks>
/// This method modifies <see cref="JsonSerializerSettings.ContractResolver"/>.
/// </remarks>
/// <param name="options"><see cref="MvcJsonOptions"/></param>
/// <param name="processDictionaryKeys">If true will camel case dictionary keys and properties of dynamic objects.</param>
/// <returns><see cref="MvcJsonOptions"/> with camel case settings.</returns>
public static MvcJsonOptions UseCamelCasing(this MvcJsonOptions options, bool processDictionaryKeys)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (options.SerializerSettings.ContractResolver is DefaultContractResolver resolver)
{
resolver.NamingStrategy = new CamelCaseNamingStrategy
{
ProcessDictionaryKeys = processDictionaryKeys
};
}
else
{
if (options.SerializerSettings.ContractResolver == null)
{
throw new InvalidOperationException(Resources.FormatContractResolverCannotBeNull(nameof(JsonSerializerSettings.ContractResolver)));
}
var contractResolverName = options.SerializerSettings.ContractResolver.GetType().Name;
throw new InvalidOperationException(
Resources.FormatInvalidContractResolverForJsonCasingConfiguration(contractResolverName, nameof(DefaultContractResolver)));
}
return options;
}
/// <summary>
/// Configures the casing behavior of JSON serialization to use the member's casing for property names,
/// properties of dynamic types, and dictionary keys.
/// </summary>
/// <remarks>
/// This method modifies <see cref="JsonSerializerSettings.ContractResolver"/>.
/// </remarks>
/// <param name="options"><see cref="MvcJsonOptions"/></param>
/// <returns><see cref="MvcJsonOptions"/> with member casing settings.</returns>
public static MvcJsonOptions UseMemberCasing(this MvcJsonOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (options.SerializerSettings.ContractResolver is DefaultContractResolver resolver)
{
resolver.NamingStrategy = new DefaultNamingStrategy();
}
else
{
if (options.SerializerSettings.ContractResolver == null)
{
throw new InvalidOperationException(Resources.FormatContractResolverCannotBeNull(nameof(JsonSerializerSettings.ContractResolver)));
}
var contractResolverName = options.SerializerSettings.ContractResolver.GetType().Name;
throw new InvalidOperationException(
Resources.FormatInvalidContractResolverForJsonCasingConfiguration(contractResolverName, nameof(DefaultContractResolver)));
}
return options;
}
}
}

View File

@ -0,0 +1,6 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Mvc.Formatters.Json.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]

View File

@ -0,0 +1,58 @@
// <auto-generated />
namespace Microsoft.AspNetCore.Mvc.Formatters.Json
{
using System.Globalization;
using System.Reflection;
using System.Resources;
internal static class Resources
{
private static readonly ResourceManager _resourceManager
= new ResourceManager("Microsoft.AspNetCore.Mvc.Formatters.Json.Resources", typeof(Resources).GetTypeInfo().Assembly);
/// <summary>
/// {0} cannot be null.
/// </summary>
internal static string ContractResolverCannotBeNull
{
get => GetString("ContractResolverCannotBeNull");
}
/// <summary>
/// {0} cannot be null.
/// </summary>
internal static string FormatContractResolverCannotBeNull(object p0)
=> string.Format(CultureInfo.CurrentCulture, GetString("ContractResolverCannotBeNull"), p0);
/// <summary>
/// Cannot configure JSON casing behavior on '{0}' contract resolver. The supported contract resolver is {1}.
/// </summary>
internal static string InvalidContractResolverForJsonCasingConfiguration
{
get => GetString("InvalidContractResolverForJsonCasingConfiguration");
}
/// <summary>
/// Cannot configure JSON casing behavior on '{0}' contract resolver. The supported contract resolver is {1}.
/// </summary>
internal static string FormatInvalidContractResolverForJsonCasingConfiguration(object p0, object p1)
=> string.Format(CultureInfo.CurrentCulture, GetString("InvalidContractResolverForJsonCasingConfiguration"), p0, p1);
private static string GetString(string name, params string[] formatterNames)
{
var value = _resourceManager.GetString(name);
System.Diagnostics.Debug.Assert(value != null);
if (formatterNames != null)
{
for (var i = 0; i < formatterNames.Length; i++)
{
value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}");
}
}
return value;
}
}
}

View File

@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ContractResolverCannotBeNull" xml:space="preserve">
<value>{0} cannot be null.</value>
</data>
<data name="InvalidContractResolverForJsonCasingConfiguration" xml:space="preserve">
<value>Cannot configure JSON casing behavior on '{0}' contract resolver. The supported contract resolver is {1}.</value>
</data>
</root>

View File

@ -0,0 +1,264 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Xunit;
namespace Microsoft.Extensions.DependencyInjection
{
public class MvcJsonOptionsExtensionsTests
{
[Fact]
public void UseCamelCasing_WillSet_CamelCasingStrategy_NameStrategy()
{
// Arrange
var options = new MvcJsonOptions();
options.SerializerSettings.ContractResolver = new DefaultContractResolver()
{
NamingStrategy = new DefaultNamingStrategy()
};
var expected = typeof(CamelCaseNamingStrategy);
// Act
options.UseCamelCasing(processDictionaryKeys: true);
var resolver = options.SerializerSettings.ContractResolver as DefaultContractResolver;
var actual = resolver.NamingStrategy;
// Assert
Assert.IsType(expected, actual);
}
[Fact]
public void UseCamelCasing_WillNot_OverrideSpecifiedNames()
{
// Arrange
var options = new MvcJsonOptions().UseCamelCasing(processDictionaryKeys: true);
var annotatedFoo = new AnnotatedFoo()
{
HelloWorld = "Hello"
};
var expected = "{\"HELLO-WORLD\":\"Hello\"}";
// Act
var actual = SerializeToJson(options, value: annotatedFoo);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UseCamelCasing_WillChange_PropertyNames()
{
// Arrange
var options = new MvcJsonOptions().UseCamelCasing(processDictionaryKeys: true);
var foo = new { TestName = "TestFoo", TestValue = 10 };
var expected = "{\"testName\":\"TestFoo\",\"testValue\":10}";
// Act
var actual = SerializeToJson(options, value: foo);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UseCamelCasing_WillChangeFirstPartBeforeSeparator_InPropertyName()
{
// Arrange
var options = new MvcJsonOptions().UseCamelCasing(processDictionaryKeys: true);
var foo = new { TestFoo_TestValue = "Test" };
var expected = "{\"testFoo_TestValue\":\"Test\"}";
// Act
var actual = SerializeToJson(options, value: foo);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UseCamelCasing_ProcessDictionaryKeys_WillChange_DictionaryKeys_IfTrue()
{
// Arrange
var options = new MvcJsonOptions().UseCamelCasing(processDictionaryKeys: true);
var dictionary = new Dictionary<string, int>
{
["HelloWorld"] = 1,
["HELLOWORLD"] = 2
};
var expected = "{\"helloWorld\":1,\"helloworld\":2}";
// Act
var actual = SerializeToJson(options, value: dictionary);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UseCamelCasing_ProcessDictionaryKeys_WillChangeFirstPartBeforeSeparator_InDictionaryKey_IfTrue()
{
// Arrange
var options = new MvcJsonOptions().UseCamelCasing(processDictionaryKeys: true);
var dictionary = new Dictionary<string, int>()
{
["HelloWorld_HelloWorld"] = 1
};
var expected = "{\"helloWorld_HelloWorld\":1}";
// Act
var actual = SerializeToJson(options, value: dictionary);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UseCamelCasing_ProcessDictionaryKeys_WillNotChangeDictionaryKeys_IfFalse()
{
// Arrange
var options = new MvcJsonOptions().UseCamelCasing(processDictionaryKeys: false);
var dictionary = new Dictionary<string, int>
{
["HelloWorld"] = 1,
["HELLO-WORLD"] = 2
};
var expected = "{\"HelloWorld\":1,\"HELLO-WORLD\":2}";
// Act
var actual = SerializeToJson(options, value: dictionary);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UseMemberCasing_WillNotChange_OverrideSpecifiedNames()
{
// Arrange
var options = new MvcJsonOptions().UseMemberCasing();
var annotatedFoo = new AnnotatedFoo()
{
HelloWorld = "Hello"
};
var expected = "{\"HELLO-WORLD\":\"Hello\"}";
// Act
var actual = SerializeToJson(options, value: annotatedFoo);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UseMemberCasing_WillSet_DefaultNamingStrategy_AsNamingStrategy()
{
// Arrange
var options = new MvcJsonOptions();
options.SerializerSettings.ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy()
};
var expected = typeof(DefaultNamingStrategy);
// Act
options.UseMemberCasing();
var resolver = options.SerializerSettings.ContractResolver as DefaultContractResolver;
var actual = resolver.NamingStrategy;
// Assert
Assert.IsType(expected, actual);
}
[Fact]
public void UseMemberCasing_WillNotChange_PropertyNames()
{
// Arrange
var options = new MvcJsonOptions().UseMemberCasing();
var foo = new { fooName = "Test", FooValue = "Value"};
var expected = "{\"fooName\":\"Test\",\"FooValue\":\"Value\"}";
// Act
var actual = SerializeToJson(options, value: foo);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UseMemberCasing_WillNotChange_DictionaryKeys()
{
// Arrange
var options = new MvcJsonOptions().UseMemberCasing();
var dictionary = new Dictionary<string, int>()
{
["HelloWorld"] = 1,
["helloWorld"] = 2,
["HELLO-WORLD"] = 3
};
var expected = "{\"HelloWorld\":1,\"helloWorld\":2,\"HELLO-WORLD\":3}";
// Act
var actual = SerializeToJson(options, value: dictionary);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void UseCamelCasing_WillThrow_IfContractResolver_IsNot_DefaultContractResolver()
{
// Arrange
var options = new MvcJsonOptions();
options.SerializerSettings.ContractResolver = new FooContractResolver();
var expectedMessage = Resources.FormatInvalidContractResolverForJsonCasingConfiguration(nameof(FooContractResolver), nameof(DefaultContractResolver));
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => options.UseCamelCasing(processDictionaryKeys: false));
Assert.Equal(expectedMessage, actual: exception.Message);
}
[Fact]
public void UseMemberCasing_WillThrow_IfContractResolver_IsNot_DefaultContractResolver()
{
// Arrange
var options = new MvcJsonOptions();
options.SerializerSettings.ContractResolver = new FooContractResolver();
var expectedMessage = Resources.FormatInvalidContractResolverForJsonCasingConfiguration(nameof(FooContractResolver), nameof(DefaultContractResolver));
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => options.UseMemberCasing());
Assert.Equal(expectedMessage, actual: exception.Message);
}
private static string SerializeToJson(MvcJsonOptions options, object value)
{
return JsonConvert.SerializeObject(
value: value,
formatting: Formatting.None,
settings: options.SerializerSettings);
}
private class AnnotatedFoo
{
[JsonProperty("HELLO-WORLD")]
public string HelloWorld { get; set; }
}
private class FooContractResolver : IContractResolver
{
public JsonContract ResolveContract(Type type)
{
throw new NotImplementedException();
}
}
}
}