3

I usually use a variety of text manipulation tools to extract a list of properties from some REST API documentation, and then use Newtonsoft.Json to add an annotation above the field in order to tell the program whilst this property may be called "DeliveryAddress" when we serialize to JSON please call it "deliveryAddress" using

[JsonProperty(PropertyName = "deliveryAddress")]
public string DeliveryAddress{ get; set; }

It seems a bit long winded so I was wondering if there was an easier way, or some feature in VS I could use to make a 'macro' of sorts to apply this annotation to a list of PascalCase properties.

3 Answers 3

2

Well that was easy, turns out I've been cluttering my code unnecessarily all this time. Hopefully this will serve as a useful question for others in my position.

There is another class level annotation that can be used here.

[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class Order
{
    public string DeliveryAddress {get;set;}
    public string FirstName {get;set;}
    [JsonProperty(NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
    public string NewlyAddedProperty {get;set;}
}

This will apply the CamelCasing upon serialization to all properties, and this can be overridden at an inline annotation level as shown above.

What a lovely library.

Sign up to request clarification or add additional context in comments.

Comments

0

Property names serialize to camelCase by default in ASP.net core.

If for some reason this is not the case or you need to customize it further, the naming strategy can manually be specified by setting the NamingStrategy in the JSON serializer settings:

services.AddMvc().AddJsonOptions(options =>
{
  var resolver = options.SerializerSettings.ContractResolver as DefaultContractResolver;
  resolver.NamingStrategy = new CamelCaseNamingStrategy();
});

Then any time you return an object from an API, it will be serialized with camel case names.

If you're manually serializing the JSON to a string, you can inject IOptions<MvcJsonOptions> to access the default serializer settings which MVC uses:

var jsonString = JsonConvert.SerializeObject(obj, options.Value.SerializerSettings);

Comments

-1

You can manually build a serializer with a case converter:

var jsonSerializersettings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var myJsonOutput = JsonConvert.DeserializeObject<object>myJsonInput.ToString(),jsonSerializersettings);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.