0

I have an object which has field in lower case with an underscore

public class Project
{   
    public int project_id { get; set; }
    public long account_id { get; set; }
    public long user_id { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public DateTime created_at { get; set; }
    public DateTime updated_at { get; set; }
}

I need to serialize in camel case when GET, POST, etc API hit the API. How can I do it?

json is like:

{
    "project_id": 10,
    "account_id": 10,
    "user_id": 10,
    "name": "string",
    "description": "string",
    "created_at": "Date",
    "updated_at": "Date"
}

I want in this format:

{
    "projectId": 10,
    "accountId": 10,
    "userId": 10,
    "name": "string",
    "description": "string",
    "createdAt": "Date",
    "updatedAt": "Date"
}
Shashwat Prakash
  • 434
  • 5
  • 14
  • 1
    And, bonus, it means you can name your properties according to C# conventions – Caius Jard Oct 22 '21 at 04:51
  • 1
    If you're using System Text Json, the process is the same but the attribute is called JsonPropertyName. If you're using JavaScriptSerializer, upgrade – Caius Jard Oct 22 '21 at 04:59

1 Answers1

0

Try using NewtonSoft's JsonProperty attribute to annotate your properties.

using Newtonsoft.Json;

public class Project
{
    [JsonProperty("projectId")]
    public int project_id { get; set; }

    [JsonProperty("accountId")]
    public long account_id { get; set; }
    // ..
    // ..
    // ..
}
Anindya Dey
  • 825
  • 1
  • 8
  • 18
  • There are lots of classes in the project. manually in every field, I can't set JsonProperty. – Shashwat Prakash Oct 22 '21 at 04:52
  • Is there anything in particular blocking you from renaming these properties to the preferred Pascal-case convention of C#? – Anindya Dey Oct 22 '21 at 04:57
  • @ShashwatPrakash first of all I would use PascalCase naming for properties and only then will wonder how to convert from/to snake_case if needed. There is newtonsoft naming strategies: [snake_case](https://www.newtonsoft.com/json/help/html/NamingStrategySnakeCase.htm) and [camelCase](https://www.newtonsoft.com/json/help/html/NamingStrategyCamelCase.htm) that you can look into and use them – Kilas Oct 22 '21 at 11:05