我需要序列化以下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?
uj5u.com熱心網友回復:
Dictionary<string, object>改為創建:
var dictionary = new Dictionary<string, object>
{
["searchText"] = "masktl_TABLE_GetMissingTables",
["$skip"] = 0,
["$top"] = 1,
["includeFacets"] = true
};
string payload = JsonConvert.SerializeObject(dictionary);
或者,如果您需要從多個地方執行此操作,請創建一個具有相關屬性的類并使用該JsonProperty屬性在 JSON 中指定名稱。
例如:
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);
uj5u.com熱心網友回復:
您是否嘗試過使用字典而不是匿名物件,
string payload = JsonConvert.SerializeObject(new Dictionary<string, object>()
{
{ "searchText", "masktl_TABLE_GetMissingTables" },
{ "$skip", 0 },
{ "$top", 1 },
{ "includeFacets", true }
});
在線試用
如果您為給定的 json 格式定義了任何模型類,那么您可以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);
在線嘗試
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/443923.html
