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

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

json.net - Issue with serializing 'object' with System.Text.Json

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...