在c#中使用file's的原始格式向JSON文件中添加新数据

本文关键字:添加 文件 JSON 新数据 数据 格式 file 原始 | 更新日期: 2023-09-27 18:18:41

好的,所以我一直试图让我的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)将现有列表转换为jobobject并将其添加到我为新配置文件创建的profileData jobobject中,或者B)设置JSON格式选项,以便正确插入配置文件。我所需要的是将所有数据再缩进两层,删除第一层的括号,并在第二层的最后一个括号后面加一个逗号。

在c#中使用file's的原始格式向JSON文件中添加新数据

你离得不远。试试这样:

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