在变量名中使用特殊字符在 c# 中序列化 Json

Serialize Json in c# with special character in variable name

我需要连载以下内容json

{
    "searchText": "masktl_TABLE_GetMissingTables",
    "$skip": 0,
    "$top": 1,
    "includeFacets": true
}

我试过了

string payload = JsonConvert.SerializeObject(new
        {
            searchText = "masktl_TABLE_GetMissingTables",
            $skip = 0,
            $top = 1,
            includeFacets = true
        });

但是我们不能把$放在变量名中。任何人都可以建议我任何其他序列化 json 的方法吗?

改为创建 Dictionary<string, object>

var dictionary = new Dictionary<string, object>
{
    ["searchText"] = "masktl_TABLE_GetMissingTables",
    ["$skip"] = 0,
    ["$top"] = 1,
    ["includeFacets"] = true
};
string payload = JsonConvert.SerializeObject(dictionary);

或者,如果您需要从多个地方执行此操作,请创建一个具有相关属性的 class 并使用 JsonProperty 属性在 [=21] 中指定名称=].

例如:

public class SearchRequest
{
    [JsonProperty("searchText")]
    public string SearchText { get; set; }

    [JsonProperty("$skip")]
    public int Skip { get; set; }

    [JsonProperty("$top")]
    public int Top { get; set; }

    [JsonProperty("includeFacets")]
    public bool IncludeFacets { get; set; }
}

var request = new SearchRequest
{
    SearchText = "masktl_TABLE_GetMissingTables",
    Skip = 0,
    Top = 1,
    IncludeFacets = true
};
string payload = JsonConvert.SerializeObject(request);

您是否尝试过使用字典而不是匿名对象,

string payload = JsonConvert.SerializeObject(new Dictionary<string, object>()
   {
        { "searchText", "masktl_TABLE_GetMissingTables" },
        { "$skip", 0 },
        { "$top", 1 },
        { "includeFacets", true }
    });

Try Online


如果您为给定的 json 格式定义了模型 class,那么您可以 JsonPropertyAttribute 在序列化时更改 属性 的名称。

声明:

public class Pagination
{
    [JsonProperty("searchText")]
    public string SearchText{ get; set; }

    [JsonProperty("$skip")]
    public int Skip { get; set; }

    [JsonProperty("$top")]
    public int Top { get; set; }

    [JsonProperty("includeFacets")]
    public bool IncludeFacets { get; set; }
}

用法:

var paginationObj = new Pagination()
{
    SearchText = "masktl_TABLE_GetMissingTables",
    Skip = 0,
    Top = 1,
    IncludeFacets = true 
};


string payload = JsonConvert.SerializeObject(paginationObj);

Try online