【问题标题】:Assign List value to Json list class将 List 值分配给 Json 列表类
【发布时间】:2019-08-04 04:21:46
【问题描述】:

我有一个列表类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的示例代码

【问题讨论】:

  • @SirRufo:抱歉,更新了所需的 JSON 输出。代码也更新了。
  • @SirRufo:这是我在dotnetfiddle.net/W49buW 添加的一个合适的例子。

标签: c# json list


【解决方案1】:

应该是:

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;
}

【讨论】:

  • 永远不要“手动”构建 JSON 或 XML 或任何结构化数据 - 您应该始终使用经过良好测试的
  • @SirRufo:请检查此示例 dotnetfiddle.net/W49buW。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-09-14
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多