【问题标题】:serialization of object from snake case to camel case [duplicate]从蛇案到骆驼案的对象序列化[重复]
【发布时间】:2021-10-22 04:37:28
【问题描述】:

我有一个带有下划线的小写字段

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; }
}

当 GET、POST 等 API 命中 API 时,我需要以驼峰形式进行序列化。 我该怎么做?

json 是这样的:

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

我想要这种格式:

{
    "projectId": 10,
    "accountId": 10,
    "userId": 10,
    "name": "string",
    "description": "string",
    "createdAt": "Date",
    "updatedAt": "Date"
}

【问题讨论】:

  • 另外,这意味着您可以根据 C# 约定命名您的属性
  • 如果你使用的是系统文本Json,过程是一样的,但是属性叫做JsonPropertyName。如果您使用的是 JavaScriptSerializer,请升级

标签: c# .net asp.net-core


【解决方案1】:

尝试使用 NewtonSoft 的 JsonProperty attribute 来注释您的属性。

using Newtonsoft.Json;

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

    [JsonProperty("accountId")]
    public long account_id { get; set; }
    // ..
    // ..
    // ..
}

【讨论】:

  • 项目中有很多类。在每个字段中手动设置,我无法设置 JsonProperty。
  • 有什么特别阻止您将这些属性重命名为 C# 的首选 Pascal-case 约定吗?
  • @ShashwatPrakash 首先我会为属性使用 PascalCase 命名,然后才会想知道如何在需要时从/转换到 snake_case。有 newtonsoft 命名策略:snake_casecamelCase,您可以查看和使用它们
猜你喜欢
  • 2020-02-10
  • 1970-01-01
  • 2020-05-03
  • 2017-05-08
  • 1970-01-01
  • 2015-05-27
  • 2021-03-31
  • 2022-06-21
  • 1970-01-01
相关资源
最近更新 更多