Welcome to OGeek Q&A 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[4] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...