0

I tryed to read a json file, edit it and then save it again, everything works fine except the order of the values in the new json file is wrong.

Here a part of the Original Json file:

"files": [
    {
        "name": "Game.cfg",
        "sections": [
            {
                "name": "Chat",
                "settings": [
                    {
                        "name": "ChatX",
                        "value": "44"
                    },
                    {
                        "name": "ChatY",
                        "value": "74"
                    },
                    {
                        "name": "Transparency",
                        "value": "0.0000"
                    }
                ]
            },

and here the the same part in the new json file i create:

"files": [
  {
    "sections": [
      {
        "settings": [
          {
            "name": "ChatX",
            "value": "44"
          },
          {
            "name": "ChatY",
            "value": "74"
          },
          {
            "name": "Transparency",
            "value": "0.0000"
          }
        ],
        "name": "Chat"
      },

and here the code if needed:

 string filename = filesource;

        var res = JsonConvert.DeserializeObject<PersistentSettings>(File.ReadAllText(filename));

        List<PersistentSettings> pers = new List<PersistentSettings>();
        pers.Add(res);

        string json = JsonConvert.SerializeObject(pers, Formatting.Indented);

        //write string to file
        File.WriteAllText("test.json", json);

like i said it works just not as it should, anyone got an idea why?

4
  • 2
    Ref : stackoverflow.com/questions/3948206/json-order-mixed-up - you should not be relying on any ordering is json, it is an unordered set of pairs. Commented May 7, 2016 at 23:24
  • @Andrew - Make that an answer, and I'll upvote it. Commented May 7, 2016 at 23:27
  • 1
    As @Andrew says, the order of key/value pairs in a JSON object is not meaningful, according to the standard. However, if the receiving system is broken and cannot handle arbitrary key/value pair orders, you can specify an order by using [JsonProperty(Order = X)]. See Order of serialized fields using JSON.NET. Commented May 7, 2016 at 23:30
  • 1
    @dbc thx man thats excatly what i needed :D Commented May 7, 2016 at 23:37

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.