不幸的是,C#写了一个JSON文件,它总是只写一件事

时间:2017-03-21 14:20:18

标签: c# json json.net

我想创建一个JSON文件并对其进行描述。第一张照片展示了它的外观。它应该看起来像第二张图片。因此我的编程代码是错误的。有人有解决方案吗?因为当我启动我的代码所以它总是只写一个,其他东西他总是覆盖。如何使它像第二个(带标题(dxfFiles,vipFile)和结构)?< / p>

感谢您的回答

Pic 1

Pic 2

JObject j = null;
foreach (Detection v in listVIP)
{
    j = new JObject(
        new JProperty("Dateiname", v.m_sFilename),
        new JProperty("Objekt-ID", v.m_sObjectID),
        new JProperty("Unterordner", v.m_sSubfolder),
        new JProperty("Url-Download", v.m_sDownloadlink)
    );

    foreach (Detection d in listDXF)
    {
        j = new JObject(
          new JProperty("Dateiname", d.m_sFilename),
          new JProperty("Objekt-ID", d.m_sObjectID),
          new JProperty("Unterordner", d.m_sSubfolder),
          new JProperty("Url-Download", d.m_sDownloadlink)
        );
        j.Add("Dateiname", "");
    }
}
File.WriteAllText(
  (Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\test.json"), j.ToString()
);

1 个答案:

答案 0 :(得分:0)

您可以像这样创建所需的JSON:

JArray jaVIP = new JArray();
foreach (Detection v in listVIP)
{
    jaVIP.Add(new JObject(
        new JProperty("Dateiname", v.m_sFilename),
        new JProperty("Objekt-ID", v.m_sObjectID),
        new JProperty("Unterordner", v.m_sSubfolder),
        new JProperty("Url-Download", v.m_sDownloadlink)));
}

JArray jaDFX = new JArray();
foreach (Detection d in listDXF)
{
    jaDFX.Add(new JObject(
        new JProperty("Dateiname", d.m_sFilename),
        new JProperty("Objekt-ID", d.m_sObjectID),
        new JProperty("Unterordner", d.m_sSubfolder),
        new JProperty("Url-Download", d.m_sDownloadlink)));
}

JObject j = new JObject(
    new JProperty("dxfFiles", jaDFX),
    new JProperty("vipFile", jaVIP));

File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + 
                  "\\test.json", j.ToString());

小提琴:https://dotnetfiddle.net/RHsKk0