Home > Enterprise >  Serialize Json in c# with special character in variable name
Serialize Json in c# with special character in variable name

Time:03-15

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?

CodePudding user response:

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);

CodePudding user response:

Instead of Anonymous object, have you tried using dictionary,

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

Try Online


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.

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);

Try online

  • Related