[英]Create JSON object using System.Text.Json
I am working on migrating from Json.Net to System.Text.Json.我正在从 Json.Net 迁移到 System.Text.Json。 I am not sure how we can build json object like below code using System.Text.Json.
我不确定我们如何使用 System.Text.Json 构建 json 对象,如下面的代码。 I tried lots of workaround but nothing seems working.
我尝试了很多解决方法,但似乎没有任何效果。 I know we can do this using
JsonObject
from Dot net 6 , but I am using Dot net core 5.我知道我们可以使用 Dot net 6 中的
JsonObject
来做到这一点,但我使用的是 Dot net core 5。
Newtonsoft code:牛顿软件代码:
var json = new JObject(
new JProperty("Status", result.Status.ToString()),
new JProperty("Duration", result.TotalDuration.TotalSeconds.ToString()));
if (result.Entries.Any())
{
var entries = new JObject(result.Entries
.Select(d => new JProperty(d.Key, new JObject(new JProperty("Status", d.Value.Status.ToString()), new JProperty("Duration", d.Value.Duration.TotalSeconds.ToString()), new JProperty("Description", d.Value.Description)))));
json.Add(new JProperty("result", entries));
}
In .NET 5 you can use a combination of dictionaries and anonymous types to construct free-form JSON on the fly.在 .NET 5 中,您可以结合使用字典和匿名类型来动态构建自由格式的 JSON。 For instance, your sample code can be rewritten for System.Text.Json as follows:
例如,可以为 System.Text.Json 重写您的示例代码,如下所示:
var json = new Dictionary<string, object>
{
["Status"] = result.Status.ToString(),
["Duration"] = result.TotalDuration.TotalSeconds.ToString(NumberFormatInfo.InvariantInfo),
};
var entries = result.Entries.ToDictionary(
d => d.Key,
d => new { Status = d.Value.Status.ToString(), Duration = d.Value.Duration.TotalSeconds.ToString(NumberFormatInfo.InvariantInfo), Description = d.Value.Description } );
if (entries.Count > 0)
json.Add("result", entries);
var newJson = JsonSerializer.Serialize(json, new JsonSerializerOptions { WriteIndented = true });
Notes:笔记:
When constructing a JSON object with properties whose values have mixed types (like the root json
object in your example) use Dictionary<string, object>
(or ExpandoObject
, which implements Dictionary<string, object>
).在构造具有混合类型属性的 JSON 对象时(例如示例中的根
json
对象),请使用Dictionary<string, object>
(或ExpandoObject
,它实现Dictionary<string, object>
)。
You must use object
for the value type because System.Text.Json does not support polymorphism by default unless the declared type of the polymorphic value is object
.您必须使用
object
作为值类型,因为 System.Text.Json 默认不支持多态,除非多态值的声明类型是object
。 For confirmation, see How to serialize properties of derived classes with System.Text.Json :如需确认,请参阅如何使用 System.Text.Json 序列化派生类的属性:
You can get polymorphic serialization for lower-level objects if you define them as type
object
.如果将低级对象定义为类型
object
,则可以获得多态序列化。
When constructing a JSON object with a fixed, known set of properties, use an anonymous type object.使用一组已知的固定属性构造 JSON 对象时,请使用匿名类型对象。
When constructing a JSON object with runtime property names but fixed value types, use a typed dictionary.构造具有运行时属性名称但具有固定值类型的 JSON 对象时,请使用类型化字典。 Oftentimes LINQ's
ToDictionary()
method will fit perfectly, as is shown above.通常 LINQ 的
ToDictionary()
方法非常适合,如上所示。
Similarly, when constructing a JSON array with values that have mixed types, use List<object>
or object []
.同样,在构造具有混合类型值的 JSON 数组时,请使用
List<object>
或object []
。 A typed List<T>
or T []
may be used when all values have the same type.当所有值都具有相同的类型时,可以使用类型化的
List<T>
或T []
。
When manually formatting numbers or dates as strings, be sure to do so in the invariant locale to prevent locale-specific differences in your JSON.当手动将数字或日期格式化为字符串时,请务必在不变的语言环境中执行此操作,以防止 JSON 中特定于语言环境的差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.