ValueTuples lose their property names when serialized

  • A+
Category:Languages

While trying to serialize a named value tuple to JSON string, it loses the names assigned to items

(string type, string text) myTypes = ("A", "I am an animal"); var cnvValue = JsonConvert.SerializeObject(myTypes); 

I am expecting the serialized value as

{"type":"A","text":"I am an animal"}

but the actual results are

{"Item1":"A","Item2":"I am an animal"}

There are two things that i am interested to know

  • Why does it behave like that
  • How to get the expected output

 


How to get the expected output

Something like this:

var myTypes = new{ type = "A", text = "I am an animal"}; var cnvValue = JsonConvert.SerializeObject(myTypes); 

should work if you’re looking for a similarly terse approach. Doesn’t use ValueTuples under the hood though; this is my interpreting your question as “how can I produce this expected JSON without going to the full extent of declaring a class etc”

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: