Reputation: 3481
I'm trying to end up with JSON like this:
{"KIBANA_INDEX":"whatever"}
but when I try to use the JsonPropertyAttribute
like this:
[JsonProperty(PropertyName ="KIBANA_INDEX")]
public string KibanaIndex{ get; set; }
I end up with JSON like this instead:
{"kibanA_INDEX":"whatever"}
Is there any way to bend Newtonsoft.Json to my will?
Upvotes: 4
Views: 3180
Reputation: 129657
By default, Json.Net does not behave like that. If you provide a specific name in a [JsonProperty]
attribute, the serializer will honor it, and you should see that in your output. Here's an example program to demonstrate:
using System;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var foo = new Foo { KibanaIndex = "whatever" };
var json = JsonConvert.SerializeObject(foo);
Console.WriteLine(json);
}
}
public class Foo
{
[JsonProperty(PropertyName = "KIBANA_INDEX")]
public string KibanaIndex { get; set; }
}
Output:
{"KIBANA_INDEX":"whatever"}
Fiddle here: https://dotnetfiddle.net/N753GP
I suspect that you are actually using a CamelCasePropertyNamesContractResolver
. This resolver will cause all property names to be output as camel case, including those for which you have specified a name via a [JsonProperty]
attribute. Here's the same example again, except changed to use a CamelCasePropertyNamesContractResolver
:
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class Program
{
public static void Main()
{
var foo = new Foo { KibanaIndex = "whatever" };
var resolver = new CamelCasePropertyNamesContractResolver();
var settings = new JsonSerializerSettings { ContractResolver = resolver };
var json = JsonConvert.SerializeObject(foo, settings);
Console.WriteLine(json);
}
}
Here's the output, which should look familiar:
{"kibanA_INDEX":"whatever"}
Fiddle: https://dotnetfiddle.net/KBhreA
If this is not the behavior you want, it is easy to change. To do that, you just need to set the OverrideSpecifiedNames
property on the NamingStrategy
within the resolver to false
, as shown below. (Note that I added another property to the Foo
class in this example to show that the camel casing is still working for properties that do not have a [JsonProperty]
attribute.)
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class Program
{
public static void Main()
{
var foo = new Foo { KibanaIndex = "whatever", AnotherProperty = "whatever" };
var resolver = new CamelCasePropertyNamesContractResolver();
resolver.NamingStrategy.OverrideSpecifiedNames = false;
var settings = new JsonSerializerSettings { ContractResolver = resolver };
var json = JsonConvert.SerializeObject(foo, settings);
Console.WriteLine(json);
}
}
public class Foo
{
[JsonProperty(PropertyName = "KIBANA_INDEX")]
public string KibanaIndex { get; set; }
public string AnotherProperty { get; set; }
}
Output:
{"KIBANA_INDEX":"whatever","anotherProperty":"whatever"}
Fiddle: https://dotnetfiddle.net/0qeP3o
Upvotes: 5