【发布时间】:2020-07-10 13:33:15
【问题描述】:
所有, 在执行以下代码时,我们遇到了以下异常(粗体),我们试图将根节点“test”添加到最终的 json 结果中。我们希望在没有匿名对象或包装类的情况下实现这一目标。
“无法将 JSON 属性写入数组或作为第一个 JSON 标记。当前标记类型为“无”。
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": ""}}这样的东西吗? -
是否有理由不将该属性添加到
Customer类?是不是因为你在输出中只需要这个属性,而在应用程序的其他地方不需要? -
我知道你说“没有包装器”,但是你可以创建一个通用的包装器。类 JsonNeedsSingleRootWorkaround
{ public string Uid { get;私人套装; } = Guid.NewGuid().ToString("N"); /* 这是一个处理 json 序列化问题的 List */ public List Items { get;放; } }
标签: c# system.text.json