I'm using Json.Net for my website. I want the serializer to serialize property names in camelcase by default. I don't want it to change property names that I manually assign. I have the following code:
public class TestClass
{
public string NormalProperty { get; set; }
[JsonProperty(PropertyName = "CustomName")]
public string ConfiguredProperty { get; set; }
}
public void Experiment()
{
var data = new TestClass { NormalProperty = null,
ConfiguredProperty = null };
var result = JsonConvert.SerializeObject(data,
Formatting.None,
new JsonSerializerSettings {ContractResolver
= new CamelCasePropertyNamesContractResolver()}
);
Console.Write(result);
}
The output from Experiment
is:
{"normalProperty":null,"customName":null}
However, I want the output to be:
{"normalProperty":null,"CustomName":null}
Is this possible to achieve?
JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.
SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.
CamelCasePropertyNamesContractResolver Class. Resolves member mappings for a type, camel casing property names.
You can override the CamelCasePropertyNamesContractResolver
class like this:
class CamelCase : CamelCasePropertyNamesContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member,
MemberSerialization memberSerialization)
{
var res = base.CreateProperty(member, memberSerialization);
var attrs = member
.GetCustomAttributes(typeof(JsonPropertyAttribute),true);
if (attrs.Any())
{
var attr = (attrs[0] as JsonPropertyAttribute);
if (res.PropertyName != null)
res.PropertyName = attr.PropertyName;
}
return res;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With