I need to store an unknown JSON structure from an external API, but when I serialize the data using System.Text.Json
, the JSON output is incorrect. A working example can be found here: https://dotnetfiddle.net/k0zBAs
Example data from external API:
[{"name":"source","choices":["Email","Portal","Phone","Forum"]}]
Output from System.Text.Json.Serialize
[{"name":"source","choices":[[],[],[],[]]}]
Why doesn't this serialize properly?
Initially, I deserialize the data from the external API to a class similar to the one below using the Newtonsoft
library because it does a better job of deserializing the data than System.Text.Json
. Interestingly, Newtonsoft
will correctly serialize the data.
public class TestClass
{
[Newtonsoft.Json.JsonProperty("name"), System.Text.Json.Serialization.JsonPropertyName("name")]
public string Name { get; set; }
[Newtonsoft.Json.JsonProperty("choices"), System.Text.Json.Serialization.JsonPropertyName("choices")]
public object Choices { get; set; }
}
The Choices
data I receive could be any type but I have noticed they are commonly one of these:
Dictionary<string, string[]>
string[]
Dictionary<string, int>
Dictionary<string, long>
I have a feeling it is something to do with this Microsoft article on migrating from Newtonsoft.Json, but I don't fully understand it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…