C# JSONVERT在列表上不返回I';我在找

C# JSONVERT在列表上不返回I';我在找,c#,json.net,C#,Json.net,我有一个.NET4.5应用程序。目前我正在编写一个列表,该列表输出到一个XML文件: 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 i

我有一个.NET4.5应用程序。目前我正在编写一个列表,该列表输出到一个XML文件:

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();
}
当然,这不是很有用。更有用的是:

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

完成此任务的最佳方法是什么?

最简单的方法:
jsonvert.SerializeObject(list.ToDictionary(p=>p[0],p=>p[1])

或者您可以编写自己的自定义
JsonConverter


UPD:正如@Equalsk所指出的,只有当字符串数组中的第一个项是唯一的(text1、text2等)时,此代码(没有自定义转换器)才会工作。

最简单的方法是:
JsonConvert.SerializedObject(list.ToDictionary(p=>p[0],p=>p[1])

或者您可以编写自己的自定义
JsonConverter


UPD:正如@Equalsk所指出的,只有当字符串数组中的第一个项是唯一的(text1、text2等)时,此代码(没有自定义转换器)才有效。

您可以使用字典而不是列表来获得结果。如果只有键值对,请使用字典。如果更多,可以使用Tuple。如果没有,请将其打包并编写自己的自定义转换器。

您可以使用字典而不是列表来获得结果。如果只有键值对,请使用字典。如果更多,可以使用Tuple。如果没有,请将其打包并编写您自己的自定义转换器。

错误在于您在c#中创建了一个字符串数组列表。要获得结果,您需要一个属性为
text1,text2,…
的对象。然后您可以在此对象上运行JsonConvert。它将数组视为一行。它将始终以逗号分隔行中的列。您需要以不同的方式获得输出。错误在于您在c#中创建了一个字符串数组列表。要获得结果,您需要一个属性为
text1,text2,…
的对象。然后您可以在此对象上运行JsonConvert。它将数组视为一行。它将始终以逗号分隔行中的列。您需要以不同的方式获得输出。OP应该知道,这仅在[0]数组字符串唯一时有效。OP应该知道,这仅在[0]数组字符串唯一时有效。
[
    ["text1", "this is text 1"],
    ["text2", "this is text 2"],
    ["text3", "this is text 3"],
    ["text4", "this is text 4"]
]
{
  "text1": "this is text 1",
  "text2": "this is text 2",
  "text3": "this is text 3",
  "text4": "this is text 4"
}