Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Serialize Json in c# with special character in variable name

I need to serialize the following 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Create a Dictionary<string, object> instead:

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.

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading