Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string[] to string before serializing

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?

like image 478
NaMo Avatar asked Jul 20 '26 19:07

NaMo


1 Answers

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.

like image 160
Sweeper Avatar answered Jul 23 '26 07:07

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!