Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.5k views
Welcome To Ask or Share your Answers For Others

1 Answer

等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...