All, when executing the following code we are running into the following exception (in bold), we are trying to add the rootnode "test" to the end json result. we want to achieve this without anonymous objects or wrapper classes.
"Cannot write a JSON property within an array or as the first JSON token. Current token type is 'None'.
internal static class Program
{
public static void Main(string[] args)
{
customer cust = new customer();
cust.firstname = "first";
cust.lastname = "last";
Console.WriteLine(AddRootToJson("test", cust));
}
public static string AddRootToJson(string root, object obj)
{
var msSt = new MemoryStream {Position = 0};
using var utf8JsonWriter = new Utf8JsonWriter(msSt);
utf8JsonWriter.WriteStartObject(root);
JsonSerializer.Serialize(utf8JsonWriter, obj);
utf8JsonWriter.WriteEndObject();
utf8JsonWriter.Flush();
using var reader = new StreamReader(msSt);
return reader.ReadToEnd();
}
}
public class customer
{
public string firstname;
public string lastname;
}
{"test": {"firstname": "", "lastname": ""}}?Customerclass? Is it because you just need this property in the output, but no other place in the application?