0

I would like achieve Array to JSON object conversion in C# code.

Array : [a,b,c,d,e,f]

Json: {"a":"b","c":"d","e":"f"}

I tried to serialize the Array using newtonsoft and the output is not in a key value format. The input is an array of strings and the output need to be in JSON format key/value format.

dbc
  • 104,963
  • 20
  • 228
  • 340
Anshu
  • 1
  • Does this answer your question? [How do I turn a C# object into a JSON string in .NET?](https://stackoverflow.com/questions/6201529/how-do-i-turn-a-c-sharp-object-into-a-json-string-in-net) – Charlieface Feb 09 '21 at 17:41
  • 3
    It looks like you should iterate over your array, taking alternate values as keys or values, adding them to whatever JSON library representation you're using (JObject). Which JSON library are you using, and have you tried anything and got stuck? – Jon Skeet Feb 09 '21 at 17:42
  • Also, what type `Array`? Is it `List`, `List` or something else? How is it defined? Is it deserialized from JSON, or constructed in memory? – dbc Feb 09 '21 at 18:36
  • Thanks for all responses. I tried serialize of the object (newtonsoft) and the output is not a key value format. The input is array of string and the output need to be in JSON format. – Anshu Feb 09 '21 at 18:47

1 Answers1

0

Given a string [] array, you can convert it to a dictionary using LINQ, then serialize the dictionary.

E.g. using :

var dictionary = array.AsPairs().ToDictionary(t => t.Key, t => t.Value);
var newJson = JsonConvert.SerializeObject(dictionary, Formatting.Indented);

Demo fiddle #1 here.

Or, to serialize with do:

var newJson = JsonSerializer.Serialize(dictionary, new JsonSerializerOptions { WriteIndented = true });

Demo fiddle #2 here.

Both options use the extension method:

public static class EnumerableExtensions
{
    public static IEnumerable<(T Key, T Value)> AsPairs<T>(this IEnumerable<T> enumerable)
    {
        return AsPairsEnumerator(enumerable ?? throw new ArgumentNullException());
        static IEnumerable<(T key, T value)> AsPairsEnumerator(IEnumerable<T> enumerable)
        {
            bool saved = false;
            T key = default;
            foreach (var item in enumerable)
            {
                if (saved)
                    yield return (key, item);
                else
                    key = item;
                saved = !saved;
            }
        }
    }
}

And generate the result

{
  "a": "b",
  "c": "d",
  "e": "f"
}
dbc
  • 104,963
  • 20
  • 228
  • 340
  • Thanks. I was able to achieve through while loop. – Anshu Feb 11 '21 at 01:39
  • @Anshu - you're welcome. If the question is answered please do [mark it as such](https://meta.stackexchange.com/q/86978). – dbc Feb 11 '21 at 02:30