public T Deserialize <T>(string hjsonData) { var jsonValue = HjsonValue.Parse(hjsonData); var jsonString = jsonValue.ToString(Stringify.Formatted); return(JsonConvert.DeserializeObject <T>(jsonString)); }
public static void LoadValues(string filePath) { DefaultValues(); JsonObject json = null; try { json = HjsonValue.Load(filePath).Qo(); Port = json["port"]; MaxQueueSize = json["max_queue_size"]; foreach (JsonObject server in json["game_servers"].Qa()) { string name = server["name"]; if (name.Length > 13) { string nameShort = name.Substring(0, 13); Console.WriteLine("Server name \"{0}\" exceeds the max length of {1}, shortening to \"{2}\"", name, 13, nameShort); name = nameShort; } GameServers.Add(name, server["ip"]); } } catch (FileNotFoundException) { Console.WriteLine("Missing config file: {0} - using default values", filePath); return; } catch (Exception) { return; } }
public static void LoadValues(string filePath) { DefaultValues(); JsonObject json = null; try { json = HjsonValue.Load(filePath).Qo(); PortSvc = json["svc"]["port"]; PortWorld = json["world"]["port"]; PortChat = json["chat"]["port"]; IpWorld = json["world"]["ip"]; IpWorld = json["chat"]["ip"]; MaxQueueSizeSvc = json["svc"]["max_queue_size"]; MaxQueueSizeWorld = json["world"]["max_queue_size"]; MaxQueueSizeChat = json["chat"]["max_queue_size"]; WorldTimeout = json["world"]["timeout"]; DatabaseFile = json["database"]; } catch (FileNotFoundException) { Console.WriteLine("Missing config file: {0} - using default values", filePath); return; } catch (Exception) { return; } }
// Gets called automatically, passes in a class that contains pointers to // useful functions we need to interface with the goose. void IMod.Init() { //config stuff string configpath = Path.Combine(API.Helper.getModDirectory(this), "config.hjson"); if (!File.Exists(configpath)) { using (StreamWriter sw = File.CreateText(configpath)) { sw.Write(""); sw.Close(); } var jsonObject = new JsonObject { { "profanitiesAllowed", false } }; HjsonValue.Save(jsonObject, configpath); } //if (!config.Item1) //{ // genSwears(); //} //if (!config.Item2) //{ // genSexuals(); //} //if (!config.Item3) //{ // genOther(); //} // Subscribe to whatever events we want InjectionPoints.PostTickEvent += PostTick; }
static void Main(string[] args) { var data = HjsonValue.Load("readme.hjson").Qo(); Console.WriteLine(data.Qs("hello")); Console.WriteLine("Saving as json..."); HjsonValue.Save(data, "readme.json"); Console.WriteLine("Saving as hjson..."); HjsonValue.Save(data, "readme2.hjson"); // edit (preserve whitespace and comments) var wdata = (WscJsonObject)HjsonValue.LoadWsc(new StreamReader("readme.hjson")).Qo(); // edit like you normally would wdata["hugo"] = "value"; // optionally set order and comments: wdata.Order.Insert(2, "hugo"); wdata.Comments["hugo"] = "just another test"; var sw = new StringWriter(); HjsonValue.SaveWsc(wdata, sw); Console.WriteLine(sw.ToString()); }
//List<List<string>> swearList = new List<List<string>>(); public bool loadConfig() { string configpath = Path.Combine(API.Helper.getModDirectory(this), "config.hjson"); var jsonObject = HjsonValue.Load(configpath).Qo(); return(jsonObject.Qb("profanitiesAllowed")); }
private void LoadConfig() { var config = HjsonValue.Load("config.hjson"); this.iterationsPerSecond = config.Qo()["IterationsPerSecond"]; this.iterationTimeout = 1000d / this.iterationsPerSecond; this.movementSpeed = config.Qo()["MovementSpeed"]; this.pointSize = config.Qo()["PointSize"]; var colorString = config.Qo()["Color"].Qs().Substring(1); this.color = new Color(Convert.ToInt32(colorString.Substring(0, 2), 16), Convert.ToInt32(colorString.Substring(2, 2), 16), Convert.ToInt32(colorString.Substring(4, 2), 16)); this.attractors.Clear(); foreach (var attractor in config.Qo()["Attractors"].Qa()) { this.attractors.Add(new Vector3(attractor.Qo()["X"], attractor.Qo()["Y"], attractor.Qo()["Z"])); } var start = config.Qo()["Start"]; this.current = this.currentStart = new Vector3(start.Qo()["X"], start.Qo()["Y"], start.Qo()["Z"]); this.cube = this.BuildCube(this.color); this.currentCube = this.BuildCube(Color.Black); this.attractorCube = this.BuildCube(Color.White); }
// note: this sample uses the Hjson library directly. // Normally you would use nuget. static void Main(string[] args) { var data = HjsonValue.Load("test.hjson").Qo(); Console.WriteLine(data.Qs("hello")); Console.WriteLine("Saving as test-out.json..."); HjsonValue.Save(data, "test-out.json"); Console.WriteLine("Saving as test-out.hjson..."); HjsonValue.Save(data, "test-out.hjson"); // edit (preserve whitespace and comments) var wdata = (WscJsonObject)HjsonValue.Load("test.hjson", new HjsonOptions { KeepWsc = true }).Qo(); // edit like you normally would wdata["hugo"] = "value"; // optionally set order and comments: wdata.Order.Insert(2, "hugo"); wdata.Comments["hugo"] = "just another test"; var sw = new StringWriter(); HjsonValue.Save(wdata, sw, new HjsonOptions() { KeepWsc = true }); Console.WriteLine(sw.ToString()); }
public string Serialize <T>(T obj) { var jsonString = JsonConvert.SerializeObject(obj, Formatting.Indented); var hjsonString = HjsonValue.Parse(jsonString).Qo(); return(hjsonString.ToString(Stringify.Hjson)); }
public void DeleteSection(string section) { _content.Remove(section); HjsonValue.Save(_content, _file, new HjsonOptions { KeepWsc = true }); }
public dynamic ParseJsonString( string hjson) { // HJSON -> JSON var json = HjsonValue.Parse(hjson).ToString(); // JSON Parse return(JObject.Parse(json)); }
public override void Load(Stream stream) { var jsonString = HjsonValue.Load(stream).ToString(); var bytes = Encoding.Default.GetBytes(jsonString); using (var memStream = new MemoryStream(bytes)) { base.Load(memStream); } }
public override void Load(Stream stream) { var hjson = HjsonValue.Load(stream); using (var jsonStream = new MemoryStream()) { hjson.Save(jsonStream); jsonStream.Position = 0; base.Load(jsonStream); } }
/// <summary> /// Update file content to correctly /// handle comments. /// </summary> private void RefreshFile() { HjsonValue.Save(_content, _file, new HjsonOptions { KeepWsc = true }); _content = HjsonValue.Load(_file, new HjsonOptions { KeepWsc = true }).Qo(); }
/// <summary> /// 設定ファイルからロードする(デシリアライズする) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fileName"> /// 設定ファイルのパス</param> /// <returns> /// ロードした設定オブジェクト</returns> public static T Load <T>( string fileName, out bool isFirstLoad) where T : JsonConfigBase, new() { isFirstLoad = true; fileName = SwitchFileName(fileName); lock (JsonConfigBase.Locker) { var json = EmptyJson; if (File.Exists(fileName)) { isFirstLoad = false; json = File.ReadAllText( fileName, new UTF8Encoding(false)); } var data = default(T); try { // HJSON (コメント付きJSON) -> JSON の変換を行いつつDeserializeする data = JsonConvert.DeserializeObject( HjsonValue.Parse(json).ToString(), typeof(T), new JsonSerializerSettings() { Formatting = Formatting.Indented, DefaultValueHandling = DefaultValueHandling.Ignore, }) as T; } catch (Exception) { data = GetDefault <T>(); } if (data == null) { data = GetDefault <T>(); } if (!File.Exists(fileName)) { data?.Save(fileName); } return(data); } }
static bool test(string name, string file, bool inputCr, bool outputCr) { bool isJson = Path.GetExtension(file) == ".json"; bool shouldFail = name.StartsWith("fail"); JsonValue.Eol = outputCr?"\r\n":"\n"; var text = load(file, inputCr); try { var data = HjsonValue.Parse(text); var data1 = data.ToString(Stringify.Formatted); var hjson1 = data.ToString(Stringify.Hjson); if (!shouldFail) { var result = JsonValue.Parse(load(Path.Combine(assetsDir, name + "_result.json"), inputCr)); var data2 = result.ToString(Stringify.Formatted); var hjson2 = load(Path.Combine(assetsDir, name + "_result.hjson"), outputCr); if (data1 != data2) { return(failErr(name, "parse", data1, data2)); } if (hjson1 != hjson2) { return(failErr(name, "stringify", hjson1, hjson2)); } if (isJson) { string json1 = data.ToString(), json2 = JsonValue.Parse(text).ToString(); if (json1 != json2) { return(failErr(name, "json chk", json1, json2)); } } } else { return(failErr(name, "should fail")); } } catch (Exception e) { if (!shouldFail) { return(failErr(name, "exception", e.ToString(), "")); } } return(true); }
static Config() { if (!File.Exists(save_path)) { Instance = new Config(); Instance.Save(); return; } using (var stream = new FileStream(save_path, FileMode.Open, FileAccess.Read)) { Instance = JsonConvert.DeserializeObject <Config>(HjsonValue.Load(stream).ToString(Stringify.Plain)); } }
public static void Load() { if (!System.IO.File.Exists(s_Path)) { Instance = new Config(); Instance.Save(); return; } using (var fs = new System.IO.FileStream(s_Path, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { Instance = JsonConvert.DeserializeObject <Config>(HjsonValue.Load(fs).ToString(Stringify.Plain)); } }
public AuthContext CreateDbContext(string[] args) { var connectionString = HjsonValue.Load("config.hjson") ["Database"] [nameof(DatabaseOptions.ConnectionStrings)] [nameof(ConnectionStrings.Auth)] .ToValue().ToString(); return(new AuthContext( new DbContextOptionsBuilder <AuthContext>() .UseMySql(connectionString) .Options )); }
public static Conf loadFile(string path) { var conf = new Conf(); var obj = HjsonValue.Load(path).Qo(); if (obj != null) { conf.camera.ip = obj.Qo("camera").Qs("ip"); conf.camera.port = obj.Qo("camera").Qi("port"); conf.plc.port = obj.Qo("plc").Qs("port"); conf.plc.baudrate = obj.Qo("plc").Qi("baudrate"); conf.weigh.port = obj.Qo("weigh").Qs("port"); conf.weigh.baudrate = obj.Qo("weigh").Qi("baudrate"); } return(conf); }
public void Start() { try { cts = new CancellationTokenSource(); var configPath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "config.hjson"); if (!File.Exists(configPath)) { var exampleConfigPath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "config.hjson.example"); if (File.Exists(exampleConfigPath)) { File.Copy(exampleConfigPath, configPath); } else { throw new Exception($"config file {configPath} not found."); } } logger.Debug($"Read conncetor config file from '{configPath}'."); var json = HjsonValue.Load(configPath).ToString(); ConfigObject = JObject.Parse(json); // Check to generate certifiate and private key if not exists var certFile = ConfigObject?.connection?.credentials?.cert?.ToString() ?? null; certFile = HelperUtilities.GetFullPathFromApp(certFile); if (!File.Exists(certFile)) { var privateKeyFile = ConfigObject?.connection?.credentials?.privateKey.ToString() ?? null; privateKeyFile = HelperUtilities.GetFullPathFromApp(privateKeyFile); if (File.Exists(privateKeyFile)) { privateKeyFile = null; } CreateCertificate(certFile, privateKeyFile); } // Wait for connection to Qlik CheckQlikConnection(json); } catch (Exception ex) { logger.Fatal(ex, "Service could not be started."); } }
public void Write(string key, string value, string comment = null) { var parts = key.Split(':'); // Global key if (parts.Length is 1) { _content.Add(parts[0], value); // Add comment if present if (comment != null) { RefreshFile(); //_content.Comments[parts[0]] = comment; Comment support temporarily removed } } // Local key else if (parts.Length is 2) { // Nonexistant category if (!_content.Keys.Contains(parts[0])) { _content.Add(parts[0], new JsonObject()); } _content[parts[0]].Qo().Add(parts[1], value); // Add comment if present if (comment != null) { RefreshFile(); } } else { throw new InvalidKeyFormatException($"La clave {key} tiene un formato incorrecto."); } HjsonValue.Save(_content, _file, new HjsonOptions { KeepWsc = true }); }
public HJsonFileAdapter(string file) { _file = file; try { Directory.CreateDirectory(Path.GetDirectoryName(_file)); } catch (ArgumentException) { /* File is within local directory. */ } if (!File.Exists(file)) { HjsonValue.Save(new JsonObject(), _file); } _content = HjsonValue.Load(_file, new HjsonOptions { KeepWsc = true }).Qo(); }
public static QlikRequest Parse(DomainUser qlikUser, string appId, string jsonScript) { try { logger.Debug($"Parse script '{jsonScript}'..."); jsonScript = jsonScript.ToString(); if (IsJsonScript(jsonScript)) { //Parse HJSON or JSON logger.Debug("HJSON or JSON detected..."); jsonScript = HjsonValue.Parse(jsonScript).ToString(); } else { //YAML logger.Debug("YAML detected..."); jsonScript = ConvertYamlToJson(jsonScript); } if (jsonScript == null) { throw new Exception("The script could not be read."); } logger.Debug("Reading script properties..."); dynamic jsonObject = JObject.Parse(jsonScript); return(new QlikRequest() { QlikUser = qlikUser, AppId = appId, JsonScript = jsonScript, ManagedTaskId = jsonObject?.taskId ?? null, VersionMode = jsonObject?.versions ?? null }); } catch (Exception ex) { Error = new Exception("The request is incorrect and could not be parsed.", ex); throw Error; } }
internal Account[] Load( string json) { if (string.IsNullOrEmpty(json)) { json = "{}"; } var data = default(Account[]); data = JsonConvert.DeserializeObject( HjsonValue.Parse(json).ToString(), typeof(Account[]), new JsonSerializerSettings() { Formatting = Formatting.Indented, DefaultValueHandling = DefaultValueHandling.Ignore, }) as Account[]; this.CurrentList = data; return(data); }
static Config() { if (!File.Exists(s_path)) { Instance = new Config(); Instance.Save(); return; } using (var fs = new FileStream(s_path, FileMode.Open, FileAccess.Read)) { Instance = JsonConvert.DeserializeObject <Config>(HjsonValue.Load(fs).ToString(Stringify.Plain)); } if (Instance.API.ApiKey == "empty-key") { var rnd = new SecureRandom(); Instance.API.ApiKey = $"key-{rnd.Next()}"; Instance.Save(); Log.ForContext(Constants.SourceContextPropertyName, nameof(Config)) .Information("Created random api_key: {key}", Instance.API.ApiKey); } }
/// <summary> /// Loads the specified file into a JObject for further processing. /// </summary> private static JObject Load(string file) { JObject obj; string hjsonobj = HjsonValue.Load(file).ToString(); obj = JObject.Parse(hjsonobj); return(obj); /* * //var stream = new MemoryStream(); * //var writer = new StreamWriter(stream); * //writer.Write(hjsonobj); * //writer.Flush(); * //stream.Position = 0; * * //using (var sr = new StreamReader(stream)) * //using (JsonReader reader = new JsonTextReader(sr)) * //{ * // obj = (JObject)Serializer.Deserialize(reader); * //} */ }
static IEnumerable <object> TheTestCasesFromFileSystem() { foreach (var file in Directory.GetFiles("Cases", "*.txt", SearchOption.AllDirectories)) { var fileContent = File.ReadAllText(file).Replace("\r\n", "\n").Replace('\r', '\n'); var fileContentParts = fileContent.Split("\n\n////////////////\n\n"); var obo = fileContentParts[0]; var hjson = fileContentParts[1].TrimStart(); if (char.IsLetter(hjson[0])) { hjson = $"[{{\n { hjson } \n}}]"; } else if (hjson[0] == '{') { hjson = $"[\n { hjson } \n]"; } var parsedHjson = HjsonValue.Parse(hjson); yield return(new TestCaseData(obo, parsedHjson).SetName(Path.GetFileNameWithoutExtension(file))); } }
public void DeleteKey(string key) { var parts = key.Split(':'); // Global key if (parts.Length is 1) { _content.Remove(parts[0]); } // Local key else if (parts.Length is 2) { _content[parts[0]].Qo().Remove(parts[1]); } else { throw new InvalidKeyFormatException($"La clave {key} tiene un formato incorrecto."); } HjsonValue.Save(_content, _file, new HjsonOptions { KeepWsc = true }); }
public static Maybe <string> ConvertToJson(this string hjson) => hjson.Try(hj => HjsonValue.Parse(hj).ToString());