使用C#中的文件原始格式向JSON文件添加新数据

时间:2014-08-20 02:20:50

标签: c# json json.net

好的,所以我一直试图让我的JSON文件看起来像这样:

{
  "profiles": {
    "MinecraftSparta 1.7.10": {
      "name": "MCS 1.7.10",
      "gameDir": "C:\\Users\\Alex\\Desktop\\Minecraft Profiles\\MCS 1.7.10",
      "lastVersionId": " 1.7.10-forge10.13.0.1205",
      "javaArgs": "-Xms:2G -XX:PermSize=128m",
      "useHopperCrashService": false
    },
    "MCS 1.6.4": {
      "name": "MCS 1.6.4",
      "gameDir": "C:\\Users\\Alex\\Games\\MC Storage\\MC Profiles\\MCS 1.6.4",
      "lastVersionId": "1.6.4-Forge9.11.1.953",
      "javaDir": "C:\\Program Files\\Java\\jre7\\bin\\javaw.exe",
      "javaArgs": "-Xmx2G -Xms2G -XX:PermSize\u003d256m",
      "useHopperCrashService": false
    },
    "(Default)": {
      "name": "(Default)"
    },
    "Pheonixth": {
      "name": "Pheonixth",
      "javaArgs": "-Xmx2G",
      "allowedReleaseTypes": [
        "release",
        "snapshot"
      ]
    },
    "VoxelModPack 1.7.2": {
      "name": "VoxelModPack 1.7.2",
      "gameDir": "C:\\Users\\Alex\\Games\\MC Storage\\MC Profiles\\VoxelModPack     1.7.2\\modpacks\\voxelmodpack",
      "lastVersionId": "VoxelModPack12.0",
      "useHopperCrashService": false
    },
    "MCSMT 1.6.4": {
      "name": "MCSMT 1.6.4",
      "gameDir": "C:\\Users\\Alex\\Games\\MC Storage\\MC Profiles\\MCS MilTech",
      "lastVersionId": "1.6.4-Forge9.11.1.953",
      "javaArgs": "-Xmx3G -XX:PermSize\u003d256m"
    },
    "Forge": {
      "name": "Forge",
      "lastVersionId": "1.7.10-Forge10.13.0.1205"
    },
    "MCS 1.7.10 MCF_LL": {
      "name": "MCS 1.7.10 MCF_LL",
      "gameDir": "C:\\Users\\Alex\\Games\\MC Storage\\MC Profiles\\MCS 1.7.10",
      "lastVersionId": "1.7.10-LiteLoader1.7.10-1.7.10-Forge10.13.0.1205",
      "javaArgs": "-Xmx5G -XX:PermSize\u003d256m -XX:MaxPermSize\u003d1024m -    XX:+AggressiveOpts",
      "useHopperCrashService": false
    },
    "Vanilla Shaders": {
      "name": "Vanilla Shaders",
      "gameDir": "C:\\Users\\Alex\\Games\\MC Storage\\MC Profiles\\VanillaShaders",
      "lastVersionId": "1.7.2-Forge10.12.2.1121",
      "javaArgs": "-Xmx3G -XX:PermSize\u003d256m",
      "useHopperCrashService": false
    }
  },
  "selectedProfile": "MCS 1.7.10 MCF_LL",
  "clientToken": "34991388-9013-4d70-adf4-bd23fcde815f",
  "authenticationDatabase": {
    "0ac415de578c4370b179d1c0e6fd0294": {
      "displayName": "Pheonixth",
      "userProperties": [
        {
          "name": "twitch_access_token",
          "value": "o1sqtpskynapu9fl8thr2iaxlprbktz"
        }
      ],
      "accessToken": "9ba0087d00a94eb5a9161b3b9d4c98ac",
      "userid": "e10e0e032feb499da943d045a72e7c26",
      "uuid": "0ac415de-578c-4370-b179-d1c0e6fd0294",
      "username": "dietodeath23@gmail.com"
    }
  },
  "selectedUser": "0ac415de578c4370b179d1c0e6fd0294",
  "launcherVersion": {
    "name": "1.5.2",
    "format": 17
  }
}

然而,我最终得到了这个:

{
  "profiles": {
{
  "MinecraftSparta 1.7.10": {
    "name": "MCS 1.7.10",
    "gameDir": "C:\\Users\\Alex\\Desktop\\Minecraft Profiles\\MCS 1.7.10",
    "lastVersionId": " 1.7.10-forge10.13.0.1205",
    "javaArgs": "-Xms:2G -XX:PermSize=128m",
    "useHopperCrashService": false
  }
}
    "MCS 1.6.4": {
      "name": "MCS 1.6.4",
      "gameDir": "C:\\Users\\Alex\\Games\\MC Storage\\MC Profiles\\MCS 1.6.4",
      "lastVersionId": "1.6.4-Forge9.11.1.953",
      "javaDir": "C:\\Program Files\\Java\\jre7\\bin\\javaw.exe",
      "javaArgs": "-Xmx2G -Xms2G -XX:PermSize\u003d256m",
      "useHopperCrashService": false
    },
    "(Default)": {
      "name": "(Default)"
    },
    "Pheonixth": {
      "name": "Pheonixth",
      "javaArgs": "-Xmx2G",
      "allowedReleaseTypes": [
        "release",
        "snapshot"
      ]
    },
    "VoxelModPack 1.7.2": {
      "name": "VoxelModPack 1.7.2",
      "gameDir": "C:\\Users\\Alex\\Games\\MC Storage\\MC Profiles\\VoxelModPack     1.7.2\\modpacks\\voxelmodpack",
      "lastVersionId": "VoxelModPack12.0",
      "useHopperCrashService": false
    },
    "MCSMT 1.6.4": {
      "name": "MCSMT 1.6.4",
      "gameDir": "C:\\Users\\Alex\\Games\\MC Storage\\MC Profiles\\MCS MilTech",
      "lastVersionId": "1.6.4-Forge9.11.1.953",
      "javaArgs": "-Xmx3G -XX:PermSize\u003d256m"
    },
    "Forge": {
      "name": "Forge",
      "lastVersionId": "1.7.10-Forge10.13.0.1205"
    },
    "MCS 1.7.10 MCF_LL": {
      "name": "MCS 1.7.10 MCF_LL",
      "gameDir": "C:\\Users\\Alex\\Games\\MC Storage\\MC Profiles\\MCS 1.7.10",
      "lastVersionId": "1.7.10-LiteLoader1.7.10-1.7.10-Forge10.13.0.1205",
      "javaArgs": "-Xmx5G -XX:PermSize\u003d256m -XX:MaxPermSize\u003d1024m -    XX:+AggressiveOpts",
      "useHopperCrashService": false
    },
    "Vanilla Shaders": {
      "name": "Vanilla Shaders",
      "gameDir": "C:\\Users\\Alex\\Games\\MC Storage\\MC Profiles\\VanillaShaders",
      "lastVersionId": "1.7.2-Forge10.12.2.1121",
      "javaArgs": "-Xmx3G -XX:PermSize\u003d256m",
      "useHopperCrashService": false
    }
  },
  "selectedProfile": "MCS 1.7.10 MCF_LL",
  "clientToken": "34991388-9013-4d70-adf4-bd23fcde815f",
  "authenticationDatabase": {
    "0ac415de578c4370b179d1c0e6fd0294": {
      "displayName": "Pheonixth",
      "userProperties": [
        {
          "name": "twitch_access_token",
          "value": "o1sqtpskynapu9fl8thr2iaxlprbktz"
        }
      ],
      "accessToken": "9ba0087d00a94eb5a9161b3b9d4c98ac",
      "userid": "e10e0e032feb499da943d045a72e7c26",
      "uuid": "0ac415de-578c-4370-b179-d1c0e6fd0294",
      "username": "dietodeath23@gmail.com"
    }
  },
  "selectedUser": "0ac415de578c4370b179d1c0e6fd0294",
  "launcherVersion": {
    "name": "1.5.2",
    "format": 17
  }
} 

这是我的代码:

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Schema;

namespace MCS_Installer
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            string user = Environment.UserName.ToString();
            string filePath = @"C:\Users\" + user +     @"\AppData\Roaming\.minecraft\launcher_profiles.json";
            var createDirectory = System.IO.Directory.CreateDirectory (@"C:\Users\" + user + @"\Desktop\Minecraft Profiles\MCS 1.7.10");
            string directory = @"C:\Users\" + user + @"\Desktop\Minecraft Profiles\MCS 1.7.10";
            List<string> profileList = new List<string>();

            Console.WriteLine ("Finding Existing Profiles...");

            using (StreamReader reader = File.OpenText (filePath)) 
            {
                JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
                Console.WriteLine (o);
            }

            JObject profileData = 
                new JObject (
                    new JProperty ("MinecraftSparta 1.7.10",
                        new JObject (
                            new JProperty ("name", "MCS 1.7.10"),
                            new JProperty ("gameDir", directory),
                            new JProperty ("lastVersionId", " 1.7.10-forge10.13.0.1205"),
                            new JProperty ("javaArgs", "-Xms:2G -XX:PermSize=128m"),
                            new JProperty ("useHopperCrashService", false)
                        )
                    )
                );

            var profileToAdd = JsonConvert.SerializeObject(profileData, Formatting.Indented);

            foreach (string str in File.ReadAllLines(filePath)) 
            {
                profileList.Add (str);
            }

            profileList.Insert (2, profileToAdd);

            using (File.Create (filePath)) {}

            foreach (string str in profileList) {
                File.AppendAllText (filePath, str + Environment.NewLine);
            }

            Console.WriteLine ("Extracting Mods to directory...");

            ExtractMods (directory);

            Console.WriteLine ("Added Minecraft Sparta Version 1.7.10 profile to     Launcher.");
            Console.ReadLine ();
        }

        internal class Profile
        {
            public string name { get; set; }
            public string gameDir { get; set; }
            public string lastVersionId { get; set; }
            public string javaArgs { get; set; }
            public bool useHopperCrashService { get; set; }
        }

        public static void ExtractMods(string destinationPath)
        {
            string targetPath = "MCS 1.7.10_Ver2.zip";
            string extractDestinationPath = destinationPath;

            System.IO.Compression.ZipFile.ExtractToDirectory (targetPath,     extractDestinationPath);
        }

    }
}    

基本上我坚持的是,我无法将新配置文件正确地嵌入到laucher_profiles.json文件中。每次我尝试不同的东西时,我都会在正确的位置抛出配置文件,但它不适应文件的格式。有没有办法A)将现有列表转换为JObject并将其添加到我为新配置文件创建的profileData JObject或B)设置JSON格式选项,以便正确插入配置文件。我只需要将所有数据缩进两个级别,删除第一级括号,并在第二级最后一个括号后面加一个逗号。

1 个答案:

答案 0 :(得分:1)

你不是那么遥远。试试这样:

    string json = File.ReadAllText(filePath);

    JObject jo = JObject.Parse(json);
    JObject profiles = (JObject)jo["profiles"];

    profiles.AddFirst(
        new JProperty("MinecraftSparta 1.7.10",
            new JObject(
                new JProperty("name", "MCS 1.7.10"),
                new JProperty("gameDir", directory),
                new JProperty("lastVersionId", " 1.7.10-forge10.13.0.1205"),
                new JProperty("javaArgs", "-Xms:2G -XX:PermSize=128m"),
                new JProperty("useHopperCrashService", false)
            )
        )
    );

    File.WriteAllText(filePath, jo.ToString());