我有一个最离奇的问题。我有一堆对象,我试图以JSON格式存储。包含JSON的文件将与项目引用的任何资源一起放在zip存档中。当我将对象序列化为JSON时,它很好,但是一旦文件被存档然后被提取,一些字段就会消失。
我的代码:
string root = Path.GetTempPath() + "package_root\\";
string contents = JsonConvert.SerializeObject(package, Formatting.Indented);
File.WriteAllText(root + "contents.json", contents);
byte[] buf;
_ParseResource(root, package, package.BackgroundImage);
foreach (var resource in package.Resources)
{
_ParseResource(root, package, resource);
}
if (package.PackagePath == path)
{
package.Archive.Dispose();
package.Archive = null;
}
ZipFile.CreateFromDirectory(root, outputPath, CompressionLevel.NoCompression, false);
压缩之前的JSON:
{
"Nodes":[
{
"NodeID": 0,
"NodeType": 1,
"Position": "0.0537248952329852,0.460410557184751",
"ActionType": "SimpleTextImageAction",
"Metadata": {
"ImageID": -1,
"Text": "",
"MetadataTypeID": 2,
"Tooltip": null
}
}
],
"Resources":[],
"PackageVersion": 1.0,
"BackgroundImage": {
"ResourceID": -1,
"Path": "C:\\Users\\Abion47-SSD\\Desktop\\Panorama Images\\89_-_Machu_Picchu_-_Juin_2009.jpg",
"Type": 1,
"CacheOnLoad": true,
"Origin": 2
}
}
压缩后的JSON:
{
"Nodes":[
{
"NodeType":1,
"Position":"0.0801201698474518,0.294721407624633",
"ActionType":"SimpleTextAction",
"Metadata":{
"Text":"Tooltip",
"Tooltip":null
}
}
],
"Resources":[],
"PackageVersion":1.0,
"BackgroundImage":{
"ResourceID":-1,
"Path":"C:\\Users\\Abion47\\Desktop\\Panorama Files\\89_-_Machu_Picchu_-_Juin_2009.jpg",
"Type":1,
"CacheOnLoad":true,
"Origin":2
}
}
答案 0 :(得分:1)
我无法重现您的问题。这是我用来(尝试)重现它的代码:
string root = Path.GetTempPath() + "package_root\\";
string contents =
@"{
""Nodes"":[
{
""NodeID"": 0,
""NodeType"": 1,
""Position"": ""0.0537248952329852,0.460410557184751"",
""ActionType"": ""SimpleTextImageAction"",
""Metadata"": {
""ImageID"": -1,
""Text"": """",
""MetadataTypeID"": 2,
""Tooltip"": null
}
}
],
""Resources"":[],
""PackageVersion"": 1.0,
""BackgroundImage"": {
""ResourceID"": -1,
""Path"": ""C:\\Users\\Abion47-SSD\\Desktop\\Panorama Images\\89_-_Machu_Picchu_-_Juin_2009.jpg"",
""Type"": 1,
""CacheOnLoad"": true,
""Origin"": 2
}
}";
File.WriteAllText(Path.Combine(root + "contents.json"), contents);
/* SNIP resource inclusion */
if (!Directory.Exists(root))
Directory.CreateDirectory(root);
var outDir = Path.Combine(Path.GetTempPath(), "outDir");
if (!Directory.Exists(outDir))
Directory.CreateDirectory(outDir);
var outZipFullPath = Path.Combine(outDir, "out.zip");
if (File.Exists(outZipFullPath))
File.Delete(outZipFullPath);
ZipFile.CreateFromDirectory(root, outZipFullPath, CompressionLevel.NoCompression, false);
var outContentsFile = Path.Combine(outDir, "contents.json");
if (File.Exists(outContentsFile))
File.Delete(outContentsFile);
ZipFile.Open(outZipFullPath, ZipArchiveMode.Read).Entries.First().ExtractToFile(outContentsFile);
Console.WriteLine(File.ReadAllText(outContentsFile) == contents);
为我打印true
。您很可能正在打开并比较错误的zip文件