【发布时间】:2015-12-18 08:55:57
【问题描述】:
我从维基百科生成了两个文本文件和 jpeg 文件。现在我想以 json 格式序列化所有这些文件。第一次我生成了一个短文本文件,第二次我为该位置生成了纬度和经度,第三次是图像文件作为哈希码。图像和短文本文件运行良好。但是我遇到了纬度和经度文件的问题。我的文本文件看起来像这样带有新行
Lat:54.33333333
Lon:10.13333333
我想把它放在一个数组中。 现在我用来为所有对象创建 json 的 json 类是 -
public class GeoCoordinates
{
public double Longitude { get; set; }
public double Latitude { get; set; }
}
public class POIData
{
public string ShortText { get; set; }
public GeoCoordinates GeoCoordinates { get; set; }
public List<string> Images { get; set; }
public string ToJson()
{
string json = JsonConvert.SerializeObject(this, Formatting.Indented);
return json;
}
public void FromJson(string json)
{
dynamic poi = JsonConvert.DeserializeObject<POIData>(json);
ShortText = poi.ShortText;
Images = poi.Images;
GeoCoordinates = poi.GeoCordinates;
}
// This method will create json file for Neuschwanstein_Castle
public void ToJsonForLocation(string name)
{
var startPath = Application.StartupPath;
string folderName = Path.Combine(startPath, "Text_ImageWithHash");
System.IO.Directory.CreateDirectory(folderName);
string fileName = name + ".json";
var path = Path.Combine(folderName, fileName);
var Jpeg_File = new DirectoryInfo(startPath + @"\Image\" + name).GetFiles("*.jpg");
this.ShortText = File.ReadAllText(startPath + @"\Short Text\" + name+".json");
this.GeoCoordinates = File.ReadAllLines(startPath + @"\Latitude Longitude\" + name + ".json");
this.Images = new List<string> { Jpeg_File[0].Name, Jpeg_File[1].Name };
string json = ToJson();
File.WriteAllText(path, json);
}
}
我正在尝试在数组中获取地理坐标。但根本不起作用。
我的 json 文件是这样的
[
{
"ShortText": "Kiel is the capital and most &tldr; from the wedge form of its bay ",
"GeoCordinates": null,
"Images": [
"9B9C2047.jpg",
"CAD72F59.jpg"
]
}
]
【问题讨论】:
-
您是否尝试过将您的文本文件设置为 json?这是一个简单的文本文件(如果你真的使用上面的那个)所以很明显 JSON 不会解析 TEXT 文件...
-
您需要使类可序列化。如果它是可序列化的,那么从提供的示例中并不明显。
-
@ToniKostelac 你能解释一下吗?我得到正确的短文本和图像,但不是地理坐标
-
我认为@cramopy 在他的回答中很好地总结了这一点,但是我想补充一点,您通常希望使用 [Serializable] 属性将您的类标记为可序列化。我认为这可能有助于将文本解析为 double 或任何基本类型。
标签: c# arrays json serialization