【问题标题】:Get all .json Files from a Folder and then serialize in a single .Json File using C# and JSON.Net and Serialize从文件夹中获取所有 .json 文件,然后使用 C# 和 JSON.Net 在单个 .Json 文件中序列化并序列化
【发布时间】:2016-05-27 16:38:18
【问题描述】:

我有很多 .json 文件存储在一个文件夹中。现在我想让所有这些 .json 文件在一个文件中序列化。好吧,我开始如何处理它,但没有得到正确的方法。我的单个 .json 文件看起来像这样-

{
      "Name": "Holstentor",
      "Shorttext": "The Holsten Gate is a city gate marking off the western boundary of the old center of the Hanseatic city of Lübeck. This Brick Gothic construction is one of the relics of Lübeck’s medieval city fortifications and one of two remaining city gates, the other being the Citadel Gate  Because its two round towers and arched entrance are so well known it is regarded today as a symbol of this German city, and together with the old city centre of Lübeck it has been a UNESCO World Heritage Site since 1987.\nHolstentor was built in 1464.",
      "GeoCoordinates": {
        "Longitude": 10.6797,
        "Latitude": 53.8662
      },
      "Images": [
        "https://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/Holstentor_in_L%C3%BCbeck_Frontseite_-_Zuschnitt.jpg/378px-Holstentor_in_L%C3%BCbeck_Frontseite_-_Zuschnitt.jpg"
      ]
    }

和另一个 .json 文件

{
          "Name": "Passat (ship)",
          "Shorttext": "Passat is a German four-masted steel barque and one of the Flying P-Liners, the famous sailing ships of the German shipping company F. Laeisz. The name \"Passat\" means trade wind in German. She is one of the last surviving windjammers.",
          "GeoCoordinates": {
            "Longitude": 10.88138889,
            "Latitude": 53.95805556
          },
          "Images": [
            "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/Flying_P-Liner_Passat_ship_in_Travem%C3%BCnde.jpg/400px-Flying_P-Liner_Passat_ship_in_Travem%C3%BCnde.jpg"
          ]
        }

我在每个地方都有类似的 .json 文件 10 或 15。我将此文件存储在一个文件夹中,文件夹名称是主要城市名称。

现在我想获取所有这些 .json 文件并将它们序列化到一个类似这样的文件中-

我已经以类似的方式为 json 对象生成了 c# 类-

 public class GeoCoordinates
 {
 public double Longitude { get; set; }
 public double Latitude { get; set; }
 }

public class Tourist
 {
  public string Name { get; set; }
  public string Shorttext { get; set; }
  public GeoCoordinates GeoCoordinates { get; set; }
  public List<string> Images { get; set; }
 }

 public class City
 {
  public List<Tourist> Tourist { get; set; }
 }

public class RootObject
{
  public List<City> city { get; set; }
}

我以这种方式盯着我的编码-

 static void Main(string[] args)
    {
        var startPath = Application.StartupPath;
        var cities = new List<City>();
        DirectoryInfo d = new DirectoryInfo(startPath + @"\FinalJson\Flensburg\");
        foreach (var file in d.GetFiles("*.json"))
        {
          using (StreamReader fi = File.OpenText(file.FullName))
          {
            JsonSerializer serializer = new JsonSerializer();
            City city = (City)serializer.Deserialize(fi, typeof(City));
           cities.Add(city);
         }
        }

        using (StreamWriter file = File.CreateText(@"c:\cities.json"))
        {
            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(file, cities);
        }



    }

    public virtual string FullName { get; set; }

    static void DisplayFileSystemInfoAttributes(FileSystemInfo fi)
    {
        //  Assume that this entry is a file.
        string entryType = "File";

        // Determine if entry is really a directory
        if ((fi.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
        {
            entryType = "Directory";
        }
        //  Show this entry's type, name, and creation date.
        Console.WriteLine("{0} entry {1} was created on {2:D}", entryType, fi.FullName, fi.CreationTime);
    }
}

我想以这种方式得到我的结果-

{
"Kiel": [ //city name
    {
        "Tourist": [
            {
                "Name": "Holstentor",
                "Shorttext": "The Holsten Gate is a city gate marking off the western boundary of the old center of the Hanseatic city of Lübeck. This Brick Gothic construction is one of the relics of Lübeck’s medieval city fortifications and one of two remaining city gates, the other being the Citadel Gate  Because its two round towers and arched entrance are so well known it is regarded today as a symbol of this German city, and together with the old city centre of Lübeck it has been a UNESCO World Heritage Site since 1987.\nHolstentor was built in 1464.",
                "GeoCoordinates": {
                    "Longitude": 10.6797,
                    "Latitude": 53.8662
                },
                "Images": [
                    "https://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/Holstentor_in_L%C3%BCbeck_Frontseite_-_Zuschnitt.jpg/378px-Holstentor_in_L%C3%BCbeck_Frontseite_-_Zuschnitt.jpg"
                ]
            },
 {
                "Name": "Stadion Lohmühle",
                "Shorttext": "Das Stadion an der Lohmühle, oder auch einfach nur „Lohmühle“ genannt, ist ein reines Fußballstadion in Lübeck und das größte Stadion in Schleswig-Holstein.\nEs ist die Heimat des VfB Lübeck. Nach Abriss der alten Tribüne und dem Bau der neuen Haupttribüne in den 1990er Jahren im Zuge des Aufstiegs in die 2. Bundesliga im Jahre 1996 fasst das Stadion 17.869 Plätze, darunter etwa 4.400 überdachte Sitzplätze.\n\n",
                "GeoCoordinates": {
                    "Longitude": 10.66888905,
                    "Latitude": 53.88111115
                },
                "Images": [
                    "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1c/L%C3%BCbeck-Lohm%C3%BChle_1.jpg/400px-L%C3%BCbeck-Lohm%C3%BChle_1.jpg"
                ]
            },

   //ans so on ..........

        ]

    }
  ]
}

【问题讨论】:

    标签: c# serialization json.net deserialization jsonserializer


    【解决方案1】:

    这对我有用

        using System;
        using System.Collections.Generic;
        using Newtonsoft.Json;
    
        public class RootObject
        {
            public string url_short { get; set; }
            public string url_long { get; set; }
            public int type { get; set; }
        }
    
        public class Program
        {
            static public void Main()
            {
    foreach (string fileName in Directory.GetFiles("directoryName", "*.json")
        {
           using (StreamReader r = new StreamReader(Server.MapPath(fileName)))
               {
                   string json = r.ReadToEnd();
                   List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(json);
               }
            // Do something with the file content
        }
    
            }  
        }
    

    【讨论】:

      【解决方案2】:

      我认为您正在寻找以下链接: http://www.newtonsoft.com/json/help/html/DeserializeWithJsonSerializerFromFile.htm http://www.newtonsoft.com/json/help/html/SerializeWithJsonSerializerToFile.htm

      var cities = new List<City>()
      
      foreach (var file in d.GetFiles("*.json"))
      {
        using (StreamReader fi = File.OpenText(file.FullName))
        {
          JsonSerializer serializer = new JsonSerializer();
          City city = (City)serializer.Deserialize(fi, typeof(City));
         cities.Add(city);
       }
      }
      
      using (StreamWriter file = File.CreateText(@"c:\cities.json"))
      {
          JsonSerializer serializer = new JsonSerializer();
          serializer.Serialize(file, cities);
      }
      

      这会有帮助吗?

      【讨论】:

      • 是的,但我的问题是我想将所有文件写入单个 .json 文件中,但我不知道如何读取文件夹中的每个 .json 文件
      • 我真的很喜欢这种编码。该示例只能读取一个文件。但我正在尝试获取一些 .json 文件,然后在新的 .json 文件中序列化。
      • 我有一个问题,我的文件夹中有 Flensburg Firth.json、海军学院 Mürwik.json 和 Nordertor.json 等文件。我想动态地获取它。我不想写 FlensburgFirth.json 来找到它。这就是为什么在我的代码中我想创建一个 foreach 循环。你的代码中的全名是什么?读取文件夹中任何 .json 文件的逻辑应该是什么
      • 请检查全名:msdn.microsoft.com/en-us/library/…。我猜你已经在动态地做这件事了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      • 1970-01-01
      • 2015-10-24
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多