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
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 ValueTuple
s (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”
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 ValueTuple
s. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With