1

I have such endpoint in my controller :

public async Task<<IEnumerable<ItemsList>>> GetItems()
    {
        List<ItemsList>> items = await _itemManager.GetItemsAsync();       
        return items;
    }

And when I get result from this endpoint :

{
 "Type": "SomeType",
  "Items":[{"Id":1,"ItemType":"SomeType"}] 
 }

but I want to be Camel Case, such as :

{
"type": "SomeType",
 "items":[{"id":1,"itemType":"SomeType"}] 
}

Here is of

public class ItemsList
{
    public ItemType Type { get; set; }
    public List<Items> Items { get; set; }
}

public class Item
{
    public int ItemId { get; set; }
    public ItemType ItemType { get; set; }
}

I found solution like :

public async Task<<IEnumerable<ItemsList>>> GetItems()
    {
        List<ItemsList>> items = await _itemManager.GetItemsAsync();

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

        return Json(items),serializerSettings);       
    }

So, what I want to do it's to create Attribute, which can be applied to specific endpoint and make result from the endpoint to be camelCase.

Applying Json attributes to Dto's or formatting the whole controller isn't my case.

Community
  • 1
  • 1

3 Answers3

1

On the entity, you can use:

[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]

On a property, you can use:

[JsonProperty(NamingStrategyType = typeof(CamelCaseNamingStrategy))]

Also on a property, you can manually specify the property name if you wish:

[JsonProperty(PropertyName = "myPropertyName")]
1

I like to use the DataMemberAttribute from System.Runtime.Serialization

Example:

[Serializable]
[DataContract]
public class SomeDto
{
    [DataMember(Name = "unitCount")]
    public int UnitCount { get; set; }

    [DataMember(Name = "packagingType")]
    public PackagingType PackagingTypeIdEtc { get; set; }

// ...

The output will be camelCase and you'll also be able to control things like emitDefaultValue and so on.

{
    unitCount: 3,
    packagingType: "box",
    /* ... */
}
clarkitect
  • 1,720
  • 14
  • 23
0

Try putting below in Register function under WebApiConfig

public static void Register(HttpConfiguration config)
{    
    config.Formatters.Clear();
    config.Formatters.Add(new JsonMediaTypeFormatter());
    config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
    config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractresolvder();
}
Aditya Bhave
  • 998
  • 1
  • 5
  • 10