2017-08-10 74 views
0

下面是一些簡單的代碼,它可以將.json文件反序列化,然後再次序列化它,不會對數據進行任何更改。JsonSerializer沒有序列化所有數據

JObject json = JObject.Parse(File.ReadAllText("fileIn.json")); 
JsonWriter writer = new JsonTextWriter(new StreamWriter("fileOut.json", false)); 
writer.Formatting = Formatting.Indented; 
JsonSerializer serializer = new JsonSerializer(); 
serializer.Serialize(writer, json); 

似乎一切都反序列化就好作爲json JObject包含了所有的數據,但奇怪的是不是一切都被序列化。

如果這是fileIn.json

{ 
    "metadata":{ 
     "vertices":56 
    }, 
    "influencesPerVertex":2, 
    "bones":[{ 
     "parent":-1, 
     "name":"torso", 
     "scl":[1,1,1], 
     "pos":[-2.42144e-08,0.720174,-0.00499988], 
     "rotq":[0.707107,0,-0,0.707107] 
    },{ 
     "parent":0, 
     "name":"head", 
     "scl":[1,1,1], 
     "pos":[0,0,-0.904725], 
     "rotq":[0,0,-0,1] 
    },{ 
     "parent":0, 
     "name":"leftLeg", 
     "scl":[1,1,1], 
     "pos":[0.173333,-4.05163e-05,-0], 
     "rotq":[1,-4.37114e-08,-0,0] 
    }], 
    "skinIndices":[1,2,3], 
    "vertices":[1,2,3], 
    "skinWeights":[1,2,3], 
    "faces":[1,2,3], 
    "normals":[1,2,3], 
    "uvs":[] 
} 

然後fileOut.json將這個樣子:

{ 
    "metadata": { 
    "vertices": 56 
    }, 
    "influencesPerVertex": 2, 
    "bones": [ 
    { 
     "parent": -1, 
     "name": "torso", 
     "scl": [ 
     1, 
     1, 
     1 
     ], 
     "pos": [ 
     -2.42144E-08, 
     0.720174, 
     -0.00499988 
     ], 
     "rotq": [ 
     0.707107, 
     0, 
     0, 
     0.707107 
     ] 
    }, 
    { 
     "parent": 0, 
     "name": "head", 
     "scl": [ 
     1, 
     1, 
     1 
     ], 
     "pos": [ 
     0, 
     0, 
     -0.904725 
     ], 
     "rotq": [ 
     0, 
     0, 
     0, 
     1 
     ] 
    }, 
    { 
     "parent": 0, 
     "name": "leftLeg", 
     "scl": [ 
     1, 
     1, 
     1 
     ], 
     "pos": [ 
     0.173333, 
     -4.05163E-05, 
     0 
     ], 
     "rotq": [ 
     1, 
     -4.37114E-08, 
     0, 
     0 
     ] 
    } 
    ], 
    "skinIndices": [ 
    1, 
    2, 
    3 
    ], 
    "vertices": [ 
    1, 
    2, 
    3 

正如你可以看到輸出文件丟失數據接近尾聲。爲什麼會發生這種情況,我該如何解決?由於

回答

1

你不閉上你的輸出文件(新的StreamWriter(「fileOut.json」,假),這就是爲什麼你沒有看到整個文件...

爲更簡單的方法寫縮進json回檔案將是

JObject json = JObject.Parse(File.ReadAllText("fileIn.json")); 
File.WriteAllText("fileOut.json", json.ToString(Newtonsoft.Json.Formatting.Indented)); 
+0

謝謝!這種方式更簡單。 – CasualKyle

相關問題