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?

dbc
  • 104,963
  • 20
  • 228
  • 340
Remling
  • 191
  • 1
  • 15
  • 2
    Ref : http://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. – Andrew May 07 '16 at 23:24
  • @Andrew - Make that an answer, and I'll upvote it. – Wesley Long May 07 '16 at 23:27
  • 1
    As @Andrew says, the order of key/value pairs in a JSON object is not meaningful, according to the [standard](http://www.json.org/). 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)]`](http://www.newtonsoft.com/json/help/html/JsonPropertyOrder.htm). See [Order of serialized fields using JSON.NET](https://stackoverflow.com/questions/3330989). – dbc May 07 '16 at 23:30
  • 1
    @dbc thx man thats excatly what i needed :D – Remling May 07 '16 at 23:37

0 Answers0