Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueTuples lose their property names when serialized

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
like image 452
mdowes Avatar asked Jan 28 '19 08:01

mdowes


Video Answer


2 Answers

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 (but anonymous types) 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”

like image 111
Caius Jard Avatar answered Sep 27 '22 18:09

Caius Jard


The names are a compiler trick. If you look at the definition for ValueTuple you'll see that its field names are just Item1, Item2, etc.

Since JsonConvert.SerializeObject was compiled well before you assigned names that you could use during your compilation, it cannot recover the names.

Method parameters/return types are decorated with attributes that indicate the names to be used when a method's signature includes ValueTuples. This allows code authored later to "see" the names by the compiler playing tricks again, but that's the "wrong way around" to be of much use here.

How to get the expected output

Introduce an explicit type, if the names of the fields/properties are so important.

like image 26
Damien_The_Unbeliever Avatar answered Sep 27 '22 19:09

Damien_The_Unbeliever