Сериализация сложного объекта JSON с использованием C#

Я пытаюсь сериализовать сложный объект JSON с помощью C#. Я получил первоначальный вывод через мой код. Но я хочу добавить еще один объект в виде массива перед моим сериализованным JSON. Я создал класс C# из моего объекта json следующим образом.

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

Мой код для получения всех сохраненных файлов.json, а затем сериализации

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

        }

        using (StreamWriter file = File.CreateText(@"C:\C# tutorial Backup\joint_josn\joint_josn\bin\Debug\cities.json"))
        {
            JsonSerializer serializer = new JsonSerializer { Formatting = Formatting.Indented };
            serializer.Serialize(file, city);

        }

     }

Но после запуска кода я получаю свой вывод таким образом:

   {
   "Tourist": [
    {
     "Name": "Flensburg Firth",
     "Shorttext": "Flensburg Firth or Flensborg Fjord  is the westernmost inlet of the Baltic Sea. It forms part of the border between Germany to the south and Denmark to the north. Its length is either 40 or 50 km, depending to the definition of its limits. It has the largest surface of all Förden and East Jutland Fjorde, which are a special type of inlets, different from geological fjords.\nTwo peninsulas, Broager peninsula on the northern side and Holnis peninsula on the southern side divide the inlet in an outer and an inner part. West of them, near the Danish coast, there are two small Islands called Okseøer.\nOn the Danish side, outer part of the northern limits of the firth is formed by the island of Als with the town of Sønderborg. Towards the west, continuing on the Danish side are Broager, Egernsund, Gråsten, Rinkenæs, Sønderhav, and Kollund.\nIn Germany at the Danish border there is Harrislee, at the inner end of the inlet the town of Flensburg, east of it on the southern shore the town of Glücksburg and the villages Munkbrarup, Langballig, Westerholz, Quern, Steinberg, Niesgrau, Gelting, and Nieby.\n\n",
    "GeoCoordinates": {
    "Longitude": 9.42901993,
    "Latitude": 54.7959404
  },
    "Images": [
    "CE3222F5.jpg"
   ]
  },
   {
    "Name": "Naval Academy Mürwik",
    "Shorttext": "The Naval Academy Mürwik is the main training establishment for all German Navy officers and replaced the German Imperial Naval Academy in Kiel.\nIt is located at Mürwik which is a part of Germany's most northern city, Flensburg. Built on a small hill directly by the coast, it overlooks the Flensburg Fjord. The main building of the academy is known for its beautiful architecture and location, and is often named the \"Red Castle\".\n\n",
    "GeoCoordinates": {
    "Longitude": 9.45944444,
     "Latitude": 54.815
    },
    "Images": [
    "34AADEDE.jpg"
   ]
   },
  {
  "Name": "Nordertor",
  "Shorttext": "The Nordertor is an old town gate in Flensburg, Germany, which was built around 1595. Today the landmark is used as a symbol for Flensburg.\n\n",
  "GeoCoordinates": {
  "Longitude": 9.43004861,
  "Latitude": 54.79541778
   },
   "Images": [
   "D02DCA3E.jpg"
    ]
   }
 ]
}

Но я также хочу добавить "Город" перед этим json и сохранить его в виде массива. Мой ожидаемый результат -

  {
  "City": [

    {
      "Tourist": [
         {
            "Name": "Flensburg Firth",
            "Shorttext": "Flensburg Firth or Flensborg Fjord  is the westernmost inlet of the Baltic Sea. It forms part of the border between Germany to the south and Denmark to the north. Its length is either 40 or 50 km, depending to the definition of its limits. It has the largest surface of all Förden and East Jutland Fjorde, which are a special type of inlets, different from geological fjords.\nTwo peninsulas, Broager peninsula on the northern side and Holnis peninsula on the southern side divide the inlet in an outer and an inner part. West of them, near the Danish coast, there are two small Islands called Okseøer.\nOn the Danish side, outer part of the northern limits of the firth is formed by the island of Als with the town of Sønderborg. Towards the west, continuing on the Danish side are Broager, Egernsund, Gråsten, Rinkenæs, Sønderhav, and Kollund.\nIn Germany at the Danish border there is Harrislee, at the inner end of the inlet the town of Flensburg, east of it on the southern shore the town of Glücksburg and the villages Munkbrarup, Langballig, Westerholz, Quern, Steinberg, Niesgrau, Gelting, and Nieby.\n\n",
            "GeoCoordinates": {
                "Longitude": 9.42901993,
                "Latitude": 54.7959404
            },
            "Images": [
                "CE3222F5.jpg"
            ]
         },
         {
            "Name": "Naval Academy Mürwik",
            "Shorttext": "The Naval Academy Mürwik is the main training establishment for all German Navy officers and replaced the German Imperial Naval Academy in Kiel.\nIt is located at Mürwik which is a part of Germany's most northern city, Flensburg. Built on a small hill directly by the coast, it overlooks the Flensburg Fjord. The main building of the academy is known for its beautiful architecture and location, and is often named the \"Red Castle\".\n\n",
            "GeoCoordinates": {
                "Longitude": 9.45944444,
                "Latitude": 54.815
            },
            "Images": [
                "34AADEDE.jpg"
            ]
         },
         {
            "Name": "Nordertor",
            "Shorttext": "The Nordertor is an old town gate in Flensburg, Germany, which was built around 1595. Today the landmark is used as a symbol for Flensburg.\n\n",
            "GeoCoordinates": {
                "Longitude": 9.43004861,
                "Latitude": 54.79541778
            },
            "Images": [
                "D02DCA3E.jpg"
             ]
           }
         ]
      }

    ]

  }

Я пытаюсь, но не могу получить свой результат. Я знаю, что мне также нужно десериализовать RootObject. Но я не мог понять, как это сделать здесь. Я хочу знать, что я должен изменить в своем коде, чтобы получить этот результат.

1 ответ

Решение

Вы не пишете RootObject в своем коде. Также вы пишете только один город вместо списка городов

    using (StreamWriter file = File.CreateText(@"C:\C# tutorial Backup\joint_josn\joint_josn\bin\Debug\cities.json"))
    {
        JsonSerializer serializer = new JsonSerializer { Formatting = Formatting.Indented };
        serializer.Serialize(file, city);

    }

Сделайте это, чтобы решить проблему

    using (StreamWriter file = File.CreateText(@"C:\C# tutorial Backup\joint_josn\joint_josn\bin\Debug\cities.json"))
    {
        JsonSerializer serializer = new JsonSerializer { Formatting = Formatting.Indented };
        serializer.Serialize(file, new RootObject { city = new List<City> { city } } );

    }

в основном мы пишем корневой объект, чтобы вы получили поле JSON "city", а также мы пишем список городов, чтобы получить массив городов в виде JSON.

Измените регистр имени поля city в классе RootObject, чтобы получить правильное значение JSON. Кроме того, вы также можете использовать атрибут JsonProperty в поле, чтобы дать имя, отличное от имени вашего поля.

например

public class RootObject
{
   [JsonProperty("MyCityName")]
   public List<City> city { get; set; }
}
Другие вопросы по тегам