JsonSerializer不会序列化所有数据

时间:2017-08-10 00:29:35

标签: c# serialization json.net deserialization jsonserializer

这里有一些简单的代码,它们反序列化.json文件,然后再次序列化,不对数据进行任何更改。

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 个答案:

答案 0 :(得分:1)

您没有关闭输出文件(新的StreamWriter(" fileOut.json",false),这就是为什么你不能看到整个文件...

将缩进的json写回文件的简单方法是

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