I know that that could be easily written by myself but probably there is a library that can do something like that. I need an easy way (static method) to create JSON with one element. Something like that one
OneElementJson("name", "value")
and have something like that
{"name":"value"}
as result. The name should be always a string, value in most cases also string but overloading for tables list will be nice.
CodePudding user response:
I just created a library for you in a minute
public string GetOneElementJson(string name, string value)
{
return "{\"" name "\":\"" value "\"}";
}
test
var json=GetOneElementJson("name", "value");
var jObject =JObject.Parse(json);
output
{"name":"value"}
CodePudding user response:
If all you need is the simple string then Serge's example is neat and simple.
If you want a more generic way of doing this then use var or Dynamic ojects and any of the JSON serializers. Here's an example from .NET Core:
Using var:
var thing2 = new { name = "value" };
string jsonString2 = System.Text.Json.JsonSerializer.Serialize(thing2);
Console.WriteLine(jsonString2);
Using Dynamic:
dynamic thing = new System.Dynamic.ExpandoObject();
thing.name = "value";
string jsonString = System.Text.Json.JsonSerializer.Serialize(thing);
Console.WriteLine(jsonString);
The result is: {"name":"value"}