This is part of my code:
Dictionary<string, string[]> dict = new Dictionary<string, string[]>();
I have added my data in dictionary, and serializing it by:
JsonConvert.SerializeObject(dict)
I want to convert string[] to string, if there is only 1 item in string array.
So if the output is:
{
"Number": ["123"],
"Names": ["John", "Harry"]
}
I want it to be as:
{
"Number": "123",
"Names": ["John", "Harry"]
}
Since there is only 1 item in the array of "123". So, how to solve this?
One way to do this is:
var newDict = dict.ToDictionary(x => x.Key,
x => x.Value.Length == 1 ? (object)x.Value.Single() : (object)x.Value);
And then serialise newDict.
The majority of the logic lies in the second argument. I decide whether to use the single element of the value part of the KVP, or the whole string array, based on the length.
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