[英]Serialize Json in c# with special character in variable name
I need to serialize the following json我需要序列化以下 json
{
"searchText": "masktl_TABLE_GetMissingTables",
"$skip": 0,
"$top": 1,
"includeFacets": true
}
I've tried this我试过这个
string payload = JsonConvert.SerializeObject(new
{
searchText = "masktl_TABLE_GetMissingTables",
$skip = 0,
$top = 1,
includeFacets = true
});
But we can not put $ in the name of a variable.但是我们不能把$放在变量名中。 Can anyone please suggest me any other way to serialize the json?任何人都可以建议我任何其他方式来序列化 json 吗?
Create a Dictionary<string, object>
instead:创建一个Dictionary<string, object>
代替:
var dictionary = new Dictionary<string, object>
{
["searchText"] = "masktl_TABLE_GetMissingTables",
["$skip"] = 0,
["$top"] = 1,
["includeFacets"] = true
};
string payload = JsonConvert.SerializeObject(dictionary);
Alternatively, if you need to do this from more than just the one place, create a class with the relevant properties and use the JsonProperty
attribute to specify the name within the JSON.或者,如果您需要从不止一个地方执行此操作,请创建一个具有相关属性的 class,并使用JsonProperty
属性在 JSON 中指定名称。
For example:例如:
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);
Instead of Anonymous object, have you tried using dictionary,而不是匿名 object,您是否尝试过使用字典,
string payload = JsonConvert.SerializeObject(new Dictionary<string, object>()
{
{ "searchText", "masktl_TABLE_GetMissingTables" },
{ "$skip", 0 },
{ "$top", 1 },
{ "includeFacets", true }
});
If you have any defined model class for given json format then you can JsonPropertyAttribute
to change the name of property at the time of serialization.如果您为给定的 json 格式定义了 model class,那么您可以在序列化时使用JsonPropertyAttribute
更改属性名称。
Declare:宣布:
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; }
}
Usage:用法:
var paginationObj = new Pagination()
{
SearchText = "masktl_TABLE_GetMissingTables",
Skip = 0,
Top = 1,
IncludeFacets = true
};
string payload = JsonConvert.SerializeObject(paginationObj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.