首页 > 解决方案 > 从蛇案到骆驼案的对象序列化

问题描述

我有一个对象,该对象的字段为小写并带有下划线

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#.netasp.net-core

解决方案


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

using Newtonsoft.Json;

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

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

推荐阅读