Jason Axelrod
Jason Axelrod

Reputation: 7805

JsonConvert on a list not returning what I'm looking for

I have a .NET 4.5 application. Currently I am writing a list, which is outputted to an XML file:

List<string[]> list = new List<string[]> { };

list.Add(new string[] { "text1", "this is text 1" });
list.Add(new string[] { "text2", "this is text 2" });
list.Add(new string[] { "text3", "this is text 3" });
list.Add(new string[] { "text4", "this is text 4" });

using (XmlWriter writer = XmlWriter.Create("output.xml"))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("texts");

    foreach (string[] item in list)
    {
        writer.WriteElementString(item[0], item[1]);
    }

    writer.WriteEndElement();
    writer.WriteEndDocument();
}

The output of this returns as follows:

<?xml version="1.0" encoding="utf-8"?>
<texts>
    <text1>this is text 1</text1>
    <text2>this is text 2</text2>
    <text3>this is text 3</text3>
    <text4>this is text 4</text4>
</texts>

Running JsonConvert.SerializeObject() on this list returns the following:

[
    ["text1", "this is text 1"],
    ["text2", "this is text 2"],
    ["text3", "this is text 3"],
    ["text4", "this is text 4"]
]

Naturally, this is not that useful. Something more useful would be:

{
  "text1": "this is text 1",
  "text2": "this is text 2",
  "text3": "this is text 3",
  "text4": "this is text 4"
}

What would be the best way to get this done?

Upvotes: 0

Views: 135

Answers (2)

oryol
oryol

Reputation: 5248

The simplest way: JsonConvert.SerializeObject(list.ToDictionary(p => p[0], p => p[1]))

Or you can write your own custom JsonConverter

UPD: As @Equalsk pointed out this code (without custom converter) will work only if first items in string arrays are unique (text1, text2, etc.)

Upvotes: 3

Bibek Adhikari
Bibek Adhikari

Reputation: 181

You can use a Dictionary instead of list to get your result. If you have only key-value pairs use Dictionary. If more you can use Tuple. If not wrap it up and write your own custom Converter.

Upvotes: 0

Related Questions