将列表值分配给Json列表类

时间:2019-08-04 04:21:46

标签: c# json list

我有一个列表类List<Data> dataValue = new List<Data>,其中数据包含目标(多个)的列表和源(多个)的详细信息的列表。我想遍历并将每个目标和源分配给下面的列表。我终于将所有数据转换为JSON文件。

foreach (var data in dataValue)
{
    var value = new RuleJsonclassTemplate
    {
        type = data.type,

        mapping = new List<Mapping>() { new Mapping() { value = data.destination, key = data.source } },

        description = data.description,
        title = data.title
    }
}

string JSONresult = JsonConvert.SerializeObject(value);
string path = outputdir + Outputfilename;

using (var writer = new StreamWriter(path, true))
{
    writer.WriteLine(JSONresult.ToString());
    writer.Close();
}

class Mapping
{
    public string destination { get; set; }
    public string source { get; set; }
}

JSON输出应如下所示,

{
    "type": "Type1",
    "mapping": [
        {
            "value": "destination1",
            "key": "source1"
        },
        {
            "value": "destination2",
            "key": "source1"
        },
        {
            "value": "destination3",
            "key": "source3"
        }
    ],
    "description": "Test description",
    "title": "Test title"
}

能否请您提出我该如何实现的建议?供参考,我的示例代码为https://dotnetfiddle.net/W49buW

2 个答案:

答案 0 :(得分:0)

应该是:

public string ConvertToJSON(List<string>SourceStr,List<string>DestinationStr)
{
    string json = "{" + Environment.NewLine + "mapping : [" + Environment.NewLine;
    for (int i = 0; i < SourceStr.Count; i++)
     {
       json = json + "{" + Environment.NewLine + "value : " + SourceStr[i].ToString() + ","+ Environment.NewLine
                + "key : " + DestinationStr[i].ToString() + Environment.NewLine + "}," + Environment.NewLine;
     }
    json = json.Substring(0, json.LastIndexOf(','));
    json = json + "]" + Environment.NewLine + "}";
    return json;
}

答案 1 :(得分:0)

我能够通过添加另一种方法来解决该问题,该方法将数据一一添加到列表中。在https://dotnetfiddle.net/W49buW更新了我的示例代码。希望这对寻求解决方案的人们有所帮助。