Home > Back-end >  Use C# anonymous object to generate a json string where the property name is not a legal C# variable
Use C# anonymous object to generate a json string where the property name is not a legal C# variable

Time:10-26

To succinctly generate the json string {"limit": 1} in C#, I can serialize an equivalent anonymous object like so:

var s = JsonSerializer.Serialize(new { limit = 1 });

What if I want to to generate {"$limit": 1} instead? Is there any way of doing that with an anonymous object, or do I have to bring out the big guns?

CodePudding user response:

I doubt that there is a way to achieve this with anonymous objects.

You can use JsonNode API introduced in .NET 6 for System.Text.Json (the succinct syntax uses indexer and implicit conversion from int to JsonNode):

var serialize = JsonSerializer.Serialize(new JsonObject{["$limit"] = 1});

Other options: use dictionaries or create a type and use JsonPropertyNameAttribute (I assume this one is mentioned as "big guns") .

CodePudding user response:

you can try this

var json = System.Text.Json.JsonSerializer.Serialize(new Dictionary<string, int> { { "$limit", 1 } });

result

{"$limit":1}

or even more complicated

var json = System.Text.Json.JsonSerializer.Serialize(new Dictionary<string, Dictionary<string, object>> { { "$limit0", new Dictionary<string, object> { { "$limit", 1 } } }});

//or 
var s = System.Text.Json.JsonSerializer.Serialize(new Dictionary<string, object> { { "$limit0", new { limit = 1 } } });

results

{"$limit0":{"$limit":1}}

//or
{"$limit0":{"limit":1}}

  • Related