简体   繁体   English

使用 System.Text.Json 创建 JSON 对象

[英]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 中特定于语言环境的差异。

Demo fiddle here .演示小提琴在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何反序列化 ReadOnlySpan<char> 使用 System.Text.Json 到 object</char> - How to deserialize ReadOnlySpan<char> to object using System.Text.Json 如何使用 System.Text.Json API 将 stream 反序列化为 object - How to deserialize stream to object using System.Text.Json APIs 如何使用 System.Text.Json 创建基于内部字段实例化给定 object 类型的 JsonConverter - How to create a JsonConverter that instantiates a given object type based on an inner field using System.Text.Json 使用 System.Text.Json 展平 object - Flatten an object with System.Text.Json System.Text.Json object 数组反序列化 - System.Text.Json object array deserialization 使用 System.Text.Json 序列化 BigInteger - Serialising BigInteger using System.Text.Json 使用System.Text.Json的JsonConverter等效项 - JsonConverter equivalent in using System.Text.Json System.Text.Json access Json object of json object using c# .net core 3.1 - System.Text.Json access Json object of json object using c# .net core 3.1 如何在使用 System.Text.ZEED8D85B2488A6C0338854Z object 的根 json object 上的类型鉴别器元素时反序列化 object - How to get deserialize object when type discriminator element on root json object using System.Text.Json 使用字典 System.Text.Json 将 json 反序列化为 object - deserialize json to object with a dictionary System.Text.Json
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM