• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Create JSON object using System.Text.Json

Resolved: Create JSON object using System.Text.Json

0
By Isaac Tonny on 18/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I am working on migrating from Json.Net to System.Text.Json. I am not sure how we can build json object like below code using System.Text.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.
Newtonsoft code:

Answer:

In .NET 5 you can use a combination of dictionaries and anonymous types to construct free-form JSON on the fly. For instance, your sample code can be rewritten for System.Text.Json as follows:
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>).

    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. For confirmation, see How to serialize properties of derived classes with System.Text.Json:

    You can get polymorphic serialization for lower-level objects if you define them as type object.

  • When constructing a JSON object with a fixed, known set of properties, use an anonymous type object.

  • When constructing a JSON object with runtime property names but fixed value types, use a typed dictionary. Oftentimes LINQ’s ToDictionary() method will fit perfectly, as is shown above.

  • Similarly, when constructing a JSON array with values that have mixed types, use List<object> or object []. A typed List<T> or T [] may be used when all values have the same type.

  • 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.


Demo fiddle here.

If you have better answer, please add a comment about this, thank you!

asp.net-core-5.0 c# json json.net system.text.json
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Unable to run Docker .NET 6 console image

02/04/2023

Resolved: Input Focus between two React Components

02/04/2023

Resolved: linq2db throws exception when filtering by nested collection

02/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.