Json 序列化在使用 c# 的双重解析中不使用字符串行

本文关键字:字符串 序列化 Json | 更新日期: 2023-09-27 18:33:52

我想从本地文件中的内容序列化 json 对象。

这些文件包含:名称、短文本、纬度、经度和图像。

当我运行时,我的代码字符串行可以从文件中读取行,但它无法设置纬度和经度属性。引发异常。

以下是我的类和代码:

public class POIData
{
    public string Name { get; set; }
    public string Shorttext { get; set; }
    public double Longitude { get; set; }
    public double Latitude { get; set; }
    public string Image { get; set; }
 }

而 Json 序列化方法是

 public void ToJsonForLocation(string CityName,string PoiName)
    {
        var startPath = Application.StartupPath;
        string folderName = Path.Combine(startPath, "FinalJson");
        string SubfolderName = Path.Combine(folderName, CityName);
        System.IO.Directory.CreateDirectory(SubfolderName);
        string fileName = PoiName + ".json";
        var path = Path.Combine(SubfolderName, fileName);
        var Jpeg_File = new DirectoryInfo(startPath + @"'Image'" + PoiName).GetFiles("*.jpg");
        POIData Poi=new POIData();
        Poi.Name = PoiName;
        Poi.Shorttext = File.ReadAllText(startPath + @"'Short Text'" + PoiName + ".txt");
        string[] lines = File.ReadAllLines(startPath + @"'Latitude Longitude'" + PoiName + ".txt"); //in this line 2 lines occured while entering breakpoint
        Poi.Latitude = Double.Parse(lines[0].Substring(4)); //show error cannot get any data
        Poi.Longitude = Double.Parse(lines[1].Substring(4));  //show error cannot get any data
        Poi.Image=Jpeg_File[0].Name;
        string json = JsonConvert.SerializeObject(Poi,Formatting.Indented);
        File.WriteAllText(path,json);

  }

我的.txt纬度经度文件是-

  Latitude:54.79541778
  Longitude:9.43004861

我想以这种方式序列化 json-

  {
    "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....",
    "Longitude": 9.42901993,
    "Latitude": 54.7959404,
    "Image": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Flensborg_Fjord_ved_bockholmwik.jpg/400px-Flensborg_Fjord_ved_bockholmwik.jpg"
    }

双试解析行得到值

这不会获得任何值

Json 序列化在使用 c# 的双重解析中不使用字符串行

似乎问题出在这两条线上

 Poi.Latitude = Double.Parse(lines[0].Substring(4));  
 Poi.Longitude = Double.Parse(lines[1].Substring(4));  

确保添加以下空值和长度检查

    if(!string.IsNullOrEmpty(lines[0]) && lines[0].Length >= 5)
    {
       double dd ;
       Double.TryParse(lines[0].Substring(4), out dd)
       Poi.Latitude = dd; 
    }
    if(!string.IsNullOrEmpty(lines[1]) && lines[1].Length >= 5) 
    {
       double dd ;
       Double.TryParse(lines[1].Substring(4), out dd)
       Poi.Longitude = dd; 
     }

看看这是否有帮助。