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
JsonObjectfrom Dot net 6 , but I am using Dot net core 5.
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:
When constructing a JSON object with properties whose values have mixed types (like the root
jsonobject in your example) use
ExpandoObject, which implements
You must use
objectfor 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
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
object . A typed
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!