Created
August 31, 2018 21:23
-
-
Save fpintos/3aac2579a261c0cb79c9ea08db22095e to your computer and use it in GitHub Desktop.
Microsoft.OData: A factory of JSON readers that report all properties with an initial lowercase.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using System.Web.OData.Builder; | |
using Microsoft.OData.Json; | |
/// <summary> | |
/// A factory of JSON readers that report all properties with an initial lowercase. | |
/// This can be used by an ODATA service to accept payloads with mixed/incorrect case in property names. | |
/// Install it as the default IJsonReaderFactory in the service startup with this, given the IContainerBuilder builder, | |
/// ie, in the callback of MapODataServiceRoute: | |
/// var defaultServices = builder.BuildContainer(); | |
/// var defaultJsonReaderFactory = (IJsonReaderFactory)defaultServices.GetService(typeof(IJsonReaderFactory)); | |
/// builder.AddService<IJsonReaderFactory>(ServiceLifetime.Singleton, _ => new LowercasePropertyJsonReaderFactory(defaultJsonReaderFactory)); | |
/// </summary> | |
public class LowercasePropertyJsonReaderFactory : IJsonReaderFactory | |
{ | |
private IJsonReaderFactory defaultFactory; | |
public LowercasePropertyJsonReaderFactory(IJsonReaderFactory defaultFactory) | |
{ | |
this.defaultFactory = defaultFactory; | |
} | |
public IJsonReader CreateJsonReader(TextReader textReader, bool isIeee754Compatible) | |
{ | |
var defaultReader = this.defaultFactory.CreateJsonReader(textReader, isIeee754Compatible); | |
return new JsonReader(defaultReader); | |
} | |
private class JsonReader : IJsonReader | |
{ | |
private static readonly LowerCamelCaser LowerCamelCaser = new LowerCamelCaser(); | |
private IJsonReader defaultReader; | |
public JsonReader(IJsonReader defaultReader) | |
{ | |
this.defaultReader = defaultReader; | |
} | |
public object Value | |
{ | |
get | |
{ | |
var value = this.defaultReader.Value; | |
if (this.NodeType == JsonNodeType.Property && value is string strValue) | |
{ | |
value = LowerCamelCaser.ToLowerCamelCase(strValue); | |
} | |
return value; | |
} | |
} | |
public JsonNodeType NodeType => this.defaultReader.NodeType; | |
public bool IsIeee754Compatible => this.defaultReader.IsIeee754Compatible; | |
public bool Read() => this.defaultReader.Read(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment