In reference to this question:
How can I change property names when serializing with Json.net?
Sure, great, but can I have the cake and eat it?
What I'm looking for is an eye pleasing way have an alternate name for a property in such a way that the string may contain either.
Something like:
[BetterJsonProperty(PropertyName = "foo_bar")]
public string FooBar { get; set; }
Both
{
"FooBar": "yup"
}
and
{
"foo_bar":"uhuh"
}
would deserialize as expected.
As solution with no attribute would work or an attribute on the class like:
[AllowCStylePropertyNameAlternatives]
One way to accomplish this is to create a custom JsonConverter. The idea is to have the converter enumerate the JSON property names for objects we are interested in, strip the non-alphanumeric characters from the names and then try to match them up with the actual object properties via reflection. Here is how it might look in code:
public class LaxPropertyNameMatchingConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsClass;
}
public override bool CanWrite
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object instance = objectType.GetConstructor(Type.EmptyTypes).Invoke(null);
PropertyInfo[] props = objectType.GetProperties();
JObject jo = JObject.Load(reader);
foreach (JProperty jp in jo.Properties())
{
string name = Regex.Replace(jp.Name, "[^A-Za-z0-9]+", "");
PropertyInfo prop = props.FirstOrDefault(pi =>
pi.CanWrite && string.Equals(pi.Name, name, StringComparison.OrdinalIgnoreCase));
if (prop != null)
prop.SetValue(instance, jp.Value.ToObject(prop.PropertyType, serializer));
}
return instance;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
To use the custom converter with a particular class, you can decorate that class with a [JsonConverter] attribute like this:
[JsonConverter(typeof(LaxPropertyNameMatchingConverter))]
public class MyClass
{
public string MyProperty { get; set; }
public string MyOtherProperty { get; set; }
}
Here is a simple demo of the converter in action:
class Program
{
static void Main(string[] args)
{
string json = #"
[
{
""my property"" : ""foo"",
""my-other-property"" : ""bar"",
},
{
""(myProperty)"" : ""baz"",
""myOtherProperty"" : ""quux""
},
{
""MyProperty"" : ""fizz"",
""MY_OTHER_PROPERTY"" : ""bang""
}
]";
List<MyClass> list = JsonConvert.DeserializeObject<List<MyClass>>(json);
foreach (MyClass mc in list)
{
Console.WriteLine(mc.MyProperty);
Console.WriteLine(mc.MyOtherProperty);
}
}
}
Output:
foo
bar
baz
quux
fizz
bang
While this solution should do the job in most cases, there is an even simpler solution if you are OK with the idea of changing the Json.Net source code directly. It turns out you can accomplish the same thing by adding just one line of code to the Newtonsoft.Json.Serialization.JsonPropertyCollection class. In this class, there is a method called GetClosestMatchProperty() which looks like this:
public JsonProperty GetClosestMatchProperty(string propertyName)
{
JsonProperty property = GetProperty(propertyName, StringComparison.Ordinal);
if (property == null)
property = GetProperty(propertyName, StringComparison.OrdinalIgnoreCase);
return property;
}
At the point where this method is called by the deserializer, the JsonPropertyCollection contains all the properties from the class being deserialized, and the propertyName parameter contains the name of the JSON property name being matched. As you can see, the method first tries an exact name match, then it tries a case-insensitive match. So we already have a many-to-one mapping being done between the JSON and class property names.
If you modify this method to strip out all non-alphanumeric characters from the property name prior to matching it, then you can get the behavior you desire, without any special converters or attributes needed. Here is the modified code:
public JsonProperty GetClosestMatchProperty(string propertyName)
{
propertyName = Regex.Replace(propertyName, "[^A-Za-z0-9]+", "");
JsonProperty property = GetProperty(propertyName, StringComparison.Ordinal);
if (property == null)
property = GetProperty(propertyName, StringComparison.OrdinalIgnoreCase);
return property;
}
Of course, modifying the source code has its problems as well, but I figured it was worth a mention.
Another way of accomplishing this is intercepting the serialization/deserialization process early, by doing some overrides the JsonReader and JsonWriter
public class CustomJsonWriter : JsonTextWriter
{
private readonly Dictionary<string, string> _backwardMappings;
public CustomJsonWriter(TextWriter writer, Dictionary<string, string> backwardMappings)
: base(writer)
{
_backwardMappings = backwardMappings;
}
public override void WritePropertyName(string name)
{
base.WritePropertyName(_backwardMappings[name]);
}
}
public class CustomJsonReader : JsonTextReader
{
private readonly Dictionary<string, string> _forwardMappings;
public CustomJsonReader(TextReader reader, Dictionary<string, string> forwardMappings )
: base(reader)
{
_forwardMappings = forwardMappings;
}
public override object Value
{
get
{
if (TokenType != JsonToken.PropertyName)
return base.Value;
return _forwardMappings[base.Value.ToString()];
}
}
}
After doing this, you can serialize by doing
var mappings = new Dictionary<string, string>
{
{"Property1", "Equivalent1"},
{"Property2", "Equivalent2"},
};
var builder = new StringBuilder();
JsonSerializer.Create().Serialize(new CustomJsonWriter(new StringWriter(builder), mappings), your_object);
and deserialize by doing
var mappings = new Dictionary<string, string>
{
{"Equivalent1", "Property1"},
{"Equivalent2", "Property2"},
};
var txtReader = new CustomJsonReader(new StringReader(jsonString), mappings);
var your_object = JsonSerializer.Create().Deserialize<Your_Type>(txtReader);
Related
I am trying to bind my PascalCased c# model from snake_cased JSON in WebApi v2 (full framework, not dot net core).
Here's my api:
public class MyApi : ApiController
{
[HttpPost]
public IHttpActionResult DoSomething([FromBody]InputObjectDTO inputObject)
{
database.InsertData(inputObject.FullName, inputObject.TotalPrice)
return Ok();
}
}
And here's my input object:
public class InputObjectDTO
{
public string FullName { get; set; }
public int TotalPrice { get; set; }
...
}
The problem that I have is that the JSON looks like this:
{
"full_name": "John Smith",
"total_price": "20.00"
}
I am aware that I can use the JsonProperty attribute:
public class InputObjectDTO
{
[JsonProperty(PropertyName = "full_name")]
public string FullName { get; set; }
[JsonProperty(PropertyName = "total_price")]
public int TotalPrice { get; set; }
}
However my InputObjectDTO is huge, and there are many others like it too. It has hundreds of properties that are all snake cased, and it would be nice to not have to specify the JsonProperty attribute for each property. Can I make it to work "automatically"? Perhaps with a custom model binder or a custom json converter?
No need to reinvent the wheel. Json.Net already has a SnakeCaseNamingStrategy class to do exactly what you want. You just need to set it as the NamingStrategy on the DefaultContractResolver via settings.
Add this line to the Register method in your WebApiConfig class:
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() };
Here is a demo (console app) to prove the concept: https://dotnetfiddle.net/v5siz7
If you want to apply the snake casing to some classes but not others, you can do this by applying a [JsonObject] attribute specifying the naming strategy like so:
[JsonObject(NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public class InputObjectDTO
{
public string FullName { get; set; }
public decimal TotalPrice { get; set; }
}
The naming strategy set via attribute takes precedence over the naming strategy set via the resolver, so you can set your default strategy in the resolver and then use attributes to override it where needed. (There are three naming strategies included with Json.Net: SnakeCaseNamingStrategy, CamelCaseNamingStrategy and DefaultNamingStrategy.)
Now, if you want to deserialize using one naming strategy and serialize using a different strategy for the same class(es), then neither of the above solutions will work for you, because the naming strategies will be applied in both directions in Web API. So in in that case, you will need something custom like what is shown in #icepickle's answer to control when each is applied.
Well, you should be able to do it using a custom JsonConverter to read your data. Using the deserialization provided in Manojs' answer, you could create a DefaultContractResolver that would create a custom deserialization when the class has a SnakeCasedAttribute specified above.
The ContractResolver would look like the following
public class SnakeCaseContractResolver : DefaultContractResolver {
public new static readonly SnakeCaseContractResolver Instance = new SnakeCaseContractResolver();
protected override JsonContract CreateContract(Type objectType) {
JsonContract contract = base.CreateContract(objectType);
if (objectType?.GetCustomAttributes(true).OfType<SnakeCasedAttribute>().Any() == true) {
contract.Converter = new SnakeCaseConverter();
}
return contract;
}
}
The SnakeCaseConverter would be something like this?
public class SnakeCaseConverter : JsonConverter {
public override bool CanConvert(Type objectType) => objectType.GetCustomAttributes(true).OfType<SnakeCasedAttribute>().Any() == true;
private static string ConvertFromSnakeCase(string snakeCased) {
return string.Join("", snakeCased.Split('_').Select(part => part.Substring(0, 1).ToUpper() + part.Substring(1)));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
var target = Activator.CreateInstance( objectType );
var jobject = JObject.Load(reader);
foreach (var property in jobject.Properties()) {
var propName = ConvertFromSnakeCase(property.Name);
var prop = objectType.GetProperty(propName);
if (prop == null || !prop.CanWrite) {
continue;
}
prop.SetValue(target, property.Value.ToObject(prop.PropertyType, serializer));
}
return target;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
throw new NotImplementedException();
}
}
And then you could annotate your dto class using this attribute (which is just a placeholder)
[SnakeCased]
public class InputObjectDTO {
public string FullName { get; set; }
public int TotalPrice { get; set; }
}
and for reference, this is the used attribute
[AttributeUsage(AttributeTargets.Class)]
public class SnakeCasedAttribute : Attribute {
public SnakeCasedAttribute() {
// intended blank
}
}
One more thing to notice is that in your current form the JSON converter would throw an error ("20.00" is not an int), but I am going to guess that from here you can handle that part yourself :)
And for a complete reference, you could see the working version in this dotnetfiddle
You can add cusrom json converter code like below. This should allow you to specify property mapping.
public class ApiErrorConverter : JsonConverter
{
private readonly Dictionary<string, string> _propertyMappings = new Dictionary<string, string>
{
{"name", "error"},
{"code", "errorCode"},
{"description", "message"}
};
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType.GetTypeInfo().IsClass;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object instance = Activator.CreateInstance(objectType);
var props = objectType.GetTypeInfo().DeclaredProperties.ToList();
JObject jo = JObject.Load(reader);
foreach (JProperty jp in jo.Properties())
{
if (!_propertyMappings.TryGetValue(jp.Name, out var name))
name = jp.Name;
PropertyInfo prop = props.FirstOrDefault(pi =>
pi.CanWrite && pi.GetCustomAttribute<JsonPropertyAttribute>().PropertyName == name);
prop?.SetValue(instance, jp.Value.ToObject(prop.PropertyType, serializer));
}
return instance;
}
}
Then specify this attribute on your class.
This should work.
This blog explains the approach using console Application. https://www.jerriepelser.com/blog/deserialize-different-json-object-same-class/
I want to differentiate between these two json inputs in an action in Asp.Net Core:
{
"field1": null,
"field2": null
}
and
{
"field1": null,
}
I have an ordinary class like this in C#:
public class MyData
{
public string Field1 { get; set;}
public string Field2 { get; set;}
}
I want to run a partial update of an object that can accept null as the value, but when the field will not be in the input it means I don't want to update this field at all (something else from setting it to null).
This is what I ended up doing, as all other options seem to be too complicated (e.g. jsonpatch, model binding) or would not give the flexibility I want.
This solution means there is a bit of a boilerplate to write for each property, but not too much:
public class UpdateRequest : PatchRequest
{
public string Name
{
get => _name;
set { _name = value; SetHasProperty(nameof(Name)); }
}
}
public abstract class PatchRequest
{
private readonly HashSet<string> _properties = new HashSet<string>();
public bool HasProperty(string propertyName) => _properties.Contains(propertyName);
protected void SetHasProperty(string propertyName) => _properties.Add(propertyName);
}
The value can then be read like this:
if (request.HasProperty(nameof(request.Name)) { /* do something with request.Name */ }
and this is how it can be validated with a custom attribute:
var patchRequest = (PatchRequest) validationContext.ObjectInstance;
if (patchRequest.HasProperty(validationContext.MemberName) {/* do validation*/}
I've created a solution that works with System.Text.Json using a JsonConverter
DTO class:
public class MyDataDto : PatchRequest<MyDataDto>
{
public string? Field1 { get; set; }
public string? Field2 { get; set; }
}
PatchRequest class:
public abstract class PatchRequest
{
private readonly List<string> _setProperties = new();
public void MarkPropertyAsSet(string propertyName) => _setProperties.Add(propertyName);
public bool IsSet(string propertyName) => _setProperties.Contains(propertyName);
}
public abstract class PatchRequest<T> : PatchRequest where T : PatchRequest<T>
{
public bool IsSet<TProperty>(Expression<Func<T, TProperty>> expression)
=> IsSet((expression.Body as MemberExpression).Member.Name);
}
JsonConverter:
public class PatchRequestConverter : JsonConverter<PatchRequest>
{
public override bool CanConvert(Type typeToConvert) =>
typeof(PatchRequest).IsAssignableFrom(typeToConvert);
public override PatchRequest Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartObject)
throw new JsonException();
var patchRequest = (PatchRequest)Activator.CreateInstance(typeToConvert)!;
var properties = typeToConvert
.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty)
.ToDictionary(p => options.PropertyNamingPolicy?.ConvertName(p.Name) ?? p.Name);
while (reader.Read())
switch (reader.TokenType)
{
case JsonTokenType.EndObject:
return patchRequest;
case JsonTokenType.PropertyName:
var property = properties[reader.GetString()!];
reader.Read();
property.SetValue(patchRequest, JsonSerializer.Deserialize(ref reader, property.PropertyType, options));
patchRequest.MarkPropertyAsSet(property.Name);
continue;
}
throw new JsonException();
}
public override void Write(Utf8JsonWriter writer, PatchRequest value, JsonSerializerOptions options) =>
JsonSerializer.Serialize(writer, value, value.GetType(), options);
}
Register the JsonConverter like:
builder.Services.Configure<JsonOptions>(options =>
options.JsonSerializerOptions.Converters.Add(new PatchRequestConverter());
);
Use in in a API controller like:
public async Task<ActionResult> PatchMyDataAsync([FromBody] MyDataDto myDataDto)
{
var field1IsSet = myDataDto.IsSet(c => c.Field1);
var field2IsSet = myDataDto.IsSet(nameof(c.Field2));
//...
}
Just to add another 2 cents, we went the similar way to the Ilya's answer, except that we're not calling SetHasProperty from setter, but overriding DefaultContractResolver:
public class PatchRequestContractResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var prop = base.CreateProperty(member, memberSerialization);
prop.SetIsSpecified += (o, o1) =>
{
if (o is PatchRequest patchRequest)
{
patchRequest.SetHasProperty(prop.PropertyName);
}
};
return prop;
}
}
And then register this resolver in Startup:
services
.AddControllers()
.AddNewtonsoftJson(settings =>
settings.SerializerSettings.ContractResolver = new PatchRequestContractResolver());
Note, that we are still using JSON.Net and not the System.Text.Json (which is default for .NET 3+) for deserializing. As of now there's no way to do things similar to DefaultContractResolver with System.Text.Json
Intro: Asp.net core takes your request body and then deserializes to a object of Type MyData, and then it calls the method in your controller by passing the object as parameter. From the object myData you can not know if the field2 was null or not passed. Both ways the property will have a null value. The information you are trying to find is lost at deserialization.
Solution: To find out this, you need to read the request body, and check the request body if the field was passed or not. In asp.net core, there is a bit of complexity is reading the request body once it is read (by the asp.net core framework for creating the object of MyData). We need to rewind the request stream, and then read it. The code for it is below.
[HttpPost]
public void Post([FromBody] MyData myData)
{
HttpContext.Request.Body.Seek(0, System.IO.SeekOrigin.Begin);
System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Request.Body);
var requestBody = sr.ReadToEnd();
//Now check the requestBody if the field was passed using JSON parsing or string manipulation
Console.WriteLine(requestBody);
}
Warning: Though this will work. What you are trying do will reduce the readability and make it difficult for other developers. Differentiating if a field value is null or was not present in the request body is not a common practice.
A low key will be like this:
public class MyData
{
public string Field1 { get; set; }
public string Field2 { get; set; }
// this can be extension method also.
public bool HasProperty(string propertyName)
{
return GetType().GetProperty(propertyName) != null;
}
}
In main:
string json = "{ \"field1\": null, \"field2\": null }";
MyData jsonObject = null;
jsonObject = JsonConvert.DeserializeObject<MyData>(json);
MyData source= null; // this will contain values
if (jsonObject.HasProperty("Field1"))
source.Field1 = jsonObject.Field1;
Reference: Check if a property exist in a class
If I have the following classes I want to serialize using JSON.NET:
[DataContract]
public class Thing
{
[DataMember(Name = "#context")]
public string Context => "http://schema.org"
}
[DataContract]
public class Organization : Thing
{
[DataMember(Name = "address")]
public Address Address { get; set; }
...
}
[DataContract]
public class Address : Thing
{
...
}
When I use JSON.NET to serialize an Organization I get:
{
"#context": "http://schema.org",
"address": {
"#context": "http://schema.org",
...
}
...
}
What is the most efficient way of ensuring that the #context property only appears in the top level Organization object and not in the Address object?
If Organization is the only top level descendant of Thing and also no fields of type Organization may appear in serialized objects, you may easily do this by defining ShouldSerializeContext in Thing as follows:
[DataContract]
public class Thing
{
[DataMember(Name = "#context")]
public string Context => "http://schema.org";
public bool ShouldSerializeContext() { return this is Organization; }
}
Demo: https://dotnetfiddle.net/GjmfbA
If any of the Thing's descendants may act as the root object, you may need to implement a custom converter. In WriteJson method of this converter, you may filter properties to be serialized. To remove the Context property from all but the root object check writer.Path, which will be an empty string for the root object:
[DataContract]
[JsonConverter(typeof(NoContextConverter))]
public class Thing
{
[DataMember(Name = "#context")]
public string Context => "http://schema.org";
}
// ...............
public class NoContextConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var props = value.GetType().GetProperties()
.Where(p => Attribute.IsDefined(p, typeof(DataMemberAttribute)))
.ToList();
if (writer.Path != "")
props.RemoveAll(p => p.Name == "Context");
writer.WriteStartObject();
foreach (var prop in props)
{
writer.WritePropertyName(prop.GetCustomAttribute<DataMemberAttribute>().Name);
serializer.Serialize(writer, prop.GetValue(value, null));
}
writer.WriteEndObject();
}
public override bool CanConvert(Type objectType)
{
return typeof(Thing).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Demo: https://dotnetfiddle.net/cIlXID
N.B. For some reason, dotnetfiddle.net does not allow to use DataContractAttribute and DataMemberAttribute from System.Runtime.Serialization so I had to comment out relevant lines in this demo.
While #DimitryEgorov's answer is probably the correct way to go, it uses reflection which makes it slow. In the solution below, I use StringBuilder to do a string replace on the final JSON.
private const string ContextPropertyJson = "\"#context\":\"http://schema.org\",";
public override string ToString() => RemoveAllButFirstContext(
JsonConvert.SerializeObject(this, new JsonSerializerSettings));
private static string RemoveAllButFirstContext(string json)
{
var stringBuilder = new StringBuilder(json);
var startIndex = ContextPropertyJson.Length + 1;
stringBuilder.Replace(
ContextPropertyJson,
string.Empty,
startIndex,
stringBuilder.Length - startIndex - 1);
return stringBuilder.ToString();
}
I have a client which can call two different versions of a service.
One service only sends a single value:
{
"value" : { ... }
}
The second service always returns multiple values:
{
"values" : [
{ ... },
{ ... }
]
}
Ideally, I'd like to represent this with a single object in my client classes so the user never sees whether it's a single value or multiple values.
public class MyValues
{
public List<Stuff> Values { get; set; }
public Thing Other { get; set; }
}
I think that the only way I'll be able to accomplish this is with a custom JsonConverter class which I apply to MyValues, but I really only want to do something custom when I'm deserializing the property value. I can't seem to figure out if an IContractResolver would be a better way to go (e.g. somehow attach a phantom property to MyValues that deserializes value and puts it into Values.
If I create a custom converter, how to I tell it to deserialize everything else normally (e.g. if Other has an extra properties make sure they are handled appropriately, etc.)
Rather than writing a JsonConverter, you could make a set-only property Value on your MyValues, like so:
public class MyValues
{
[JsonProperty]
Stuff Value
{
set
{
(Values = Values ?? new List<Stuff>(1)).Clear();
Values.Add(value);
}
}
public List<Stuff> Values { get; set; }
public Thing Other { get; set; }
}
It could be public or private if marked with [JsonProperty]. In this case Json.NET will call the Value setter if the singleton "value" property is encountered in the JSON, and call the Values setter if the array "values" property is encountered. Since the property is set-only only the array property will be re-serialized.
To make a custom JsonConverter that has special processing for a few properties of a type but uses default processing for the remainder, you can load the JSON into a JObject, detach and process the custom properties, then populate the remainder from the JObject with JsonSerializer.Populate(), like so:
class MyValuesConverter : CustomPropertyConverterBase<MyValues>
{
protected override void ProcessCustomProperties(JObject obj, MyValues value, JsonSerializer serializer)
{
// Remove the value property for manual deserialization, and deserialize
var jValue = obj.GetValue("value", StringComparison.OrdinalIgnoreCase).RemoveFromLowestPossibleParent();
if (jValue != null)
{
(value.Values = value.Values ?? new List<Stuff>()).Clear();
value.Values.Add(jValue.ToObject<Stuff>(serializer));
}
}
}
public abstract class CustomPropertyConverterBase<T> : JsonConverter where T : class
{
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var jObj = JObject.Load(reader);
var contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(objectType);
var value = existingValue as T ?? (T)contract.DefaultCreator();
ProcessCustomProperties(jObj, value, serializer);
// Populate the remaining properties.
using (var subReader = jObj.CreateReader())
{
serializer.Populate(subReader, value);
}
return value;
}
protected abstract void ProcessCustomProperties(JObject obj, T value, JsonSerializer serializer);
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public static class JsonExtensions
{
public static JToken RemoveFromLowestPossibleParent(this JToken node)
{
if (node == null)
return null;
var contained = node.AncestorsAndSelf().Where(t => t.Parent is JContainer && t.Parent.Type != JTokenType.Property).FirstOrDefault();
if (contained != null)
contained.Remove();
// Also detach the node from its immediate containing property -- Remove() does not do this even though it seems like it should
if (node.Parent is JProperty)
((JProperty)node.Parent).Value = null;
return node;
}
}
In reference to this question:
How can I change property names when serializing with Json.net?
Sure, great, but can I have the cake and eat it?
What I'm looking for is an eye pleasing way have an alternate name for a property in such a way that the string may contain either.
Something like:
[BetterJsonProperty(PropertyName = "foo_bar")]
public string FooBar { get; set; }
Both
{
"FooBar": "yup"
}
and
{
"foo_bar":"uhuh"
}
would deserialize as expected.
As solution with no attribute would work or an attribute on the class like:
[AllowCStylePropertyNameAlternatives]
One way to accomplish this is to create a custom JsonConverter. The idea is to have the converter enumerate the JSON property names for objects we are interested in, strip the non-alphanumeric characters from the names and then try to match them up with the actual object properties via reflection. Here is how it might look in code:
public class LaxPropertyNameMatchingConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsClass;
}
public override bool CanWrite
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object instance = objectType.GetConstructor(Type.EmptyTypes).Invoke(null);
PropertyInfo[] props = objectType.GetProperties();
JObject jo = JObject.Load(reader);
foreach (JProperty jp in jo.Properties())
{
string name = Regex.Replace(jp.Name, "[^A-Za-z0-9]+", "");
PropertyInfo prop = props.FirstOrDefault(pi =>
pi.CanWrite && string.Equals(pi.Name, name, StringComparison.OrdinalIgnoreCase));
if (prop != null)
prop.SetValue(instance, jp.Value.ToObject(prop.PropertyType, serializer));
}
return instance;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
To use the custom converter with a particular class, you can decorate that class with a [JsonConverter] attribute like this:
[JsonConverter(typeof(LaxPropertyNameMatchingConverter))]
public class MyClass
{
public string MyProperty { get; set; }
public string MyOtherProperty { get; set; }
}
Here is a simple demo of the converter in action:
class Program
{
static void Main(string[] args)
{
string json = #"
[
{
""my property"" : ""foo"",
""my-other-property"" : ""bar"",
},
{
""(myProperty)"" : ""baz"",
""myOtherProperty"" : ""quux""
},
{
""MyProperty"" : ""fizz"",
""MY_OTHER_PROPERTY"" : ""bang""
}
]";
List<MyClass> list = JsonConvert.DeserializeObject<List<MyClass>>(json);
foreach (MyClass mc in list)
{
Console.WriteLine(mc.MyProperty);
Console.WriteLine(mc.MyOtherProperty);
}
}
}
Output:
foo
bar
baz
quux
fizz
bang
While this solution should do the job in most cases, there is an even simpler solution if you are OK with the idea of changing the Json.Net source code directly. It turns out you can accomplish the same thing by adding just one line of code to the Newtonsoft.Json.Serialization.JsonPropertyCollection class. In this class, there is a method called GetClosestMatchProperty() which looks like this:
public JsonProperty GetClosestMatchProperty(string propertyName)
{
JsonProperty property = GetProperty(propertyName, StringComparison.Ordinal);
if (property == null)
property = GetProperty(propertyName, StringComparison.OrdinalIgnoreCase);
return property;
}
At the point where this method is called by the deserializer, the JsonPropertyCollection contains all the properties from the class being deserialized, and the propertyName parameter contains the name of the JSON property name being matched. As you can see, the method first tries an exact name match, then it tries a case-insensitive match. So we already have a many-to-one mapping being done between the JSON and class property names.
If you modify this method to strip out all non-alphanumeric characters from the property name prior to matching it, then you can get the behavior you desire, without any special converters or attributes needed. Here is the modified code:
public JsonProperty GetClosestMatchProperty(string propertyName)
{
propertyName = Regex.Replace(propertyName, "[^A-Za-z0-9]+", "");
JsonProperty property = GetProperty(propertyName, StringComparison.Ordinal);
if (property == null)
property = GetProperty(propertyName, StringComparison.OrdinalIgnoreCase);
return property;
}
Of course, modifying the source code has its problems as well, but I figured it was worth a mention.
Another way of accomplishing this is intercepting the serialization/deserialization process early, by doing some overrides the JsonReader and JsonWriter
public class CustomJsonWriter : JsonTextWriter
{
private readonly Dictionary<string, string> _backwardMappings;
public CustomJsonWriter(TextWriter writer, Dictionary<string, string> backwardMappings)
: base(writer)
{
_backwardMappings = backwardMappings;
}
public override void WritePropertyName(string name)
{
base.WritePropertyName(_backwardMappings[name]);
}
}
public class CustomJsonReader : JsonTextReader
{
private readonly Dictionary<string, string> _forwardMappings;
public CustomJsonReader(TextReader reader, Dictionary<string, string> forwardMappings )
: base(reader)
{
_forwardMappings = forwardMappings;
}
public override object Value
{
get
{
if (TokenType != JsonToken.PropertyName)
return base.Value;
return _forwardMappings[base.Value.ToString()];
}
}
}
After doing this, you can serialize by doing
var mappings = new Dictionary<string, string>
{
{"Property1", "Equivalent1"},
{"Property2", "Equivalent2"},
};
var builder = new StringBuilder();
JsonSerializer.Create().Serialize(new CustomJsonWriter(new StringWriter(builder), mappings), your_object);
and deserialize by doing
var mappings = new Dictionary<string, string>
{
{"Equivalent1", "Property1"},
{"Equivalent2", "Property2"},
};
var txtReader = new CustomJsonReader(new StringReader(jsonString), mappings);
var your_object = JsonSerializer.Create().Deserialize<Your_Type>(txtReader);