繁体   English   中英

使用C#进行复杂的JSON对象序列化

[英]Complex JSON object Serialization using C#

我正在尝试使用C#序列化复杂的JSON对象。 我通过代码获得了初始输出,但是我想在序列化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; }
}

我获取所有存储的.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。 但是在这里找不到如何做的。我想知道我应该在代码中修改什么才能得到这个结果。

您没有在代码中写出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 } } );

    }

基本上,我们编写一个根对象,以便您获得“ city” JSON字段,此外,我们编写一个城市列表,以便将城市数组作为JSON获得。

更改“ RootObject”类中“ city”字段名称的大小写以获取正确的JSON值。 或者,您也可以在字段上使用JsonProperty属性来提供与字段名称不同的名称。

例如

public class RootObject
{
   [JsonProperty("MyCityName")]
   public List<City> city { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM