CasualKyle
CasualKyle

Reputation: 443

JsonSerializer Isn't serializing all data

Here's some simple code that deserializes a .json file then serializes it again, making no changes to the data.

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);

Everything seems to be deserialized just fine as the json JObject contains all the data but strangely not everything is being serialized.

If this is 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":[]
}

Then fileOut.json will look like this:

{
  "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

As you can see the output file is missing data towards the end. Why is this happening and how can I fix it? Thanks

Upvotes: 0

Views: 1788

Answers (1)

L.B
L.B

Reputation: 116168

You don't close your output file (new StreamWriter("fileOut.json", false), this is why you don't see the whole file...

A simpler way for writing indented json back to file would be

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

Upvotes: 2

Related Questions