public void ProcessCSharpClass() { // type: String size 1 => public string {key} { get; set;} // Define {key} NVARCHAR({size/default}; // JsonDocument.AddJsonOptions(option => //option.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase); var options = new JsonDocumentOptions { // P = JsonNamingPolicy.CamelCase, }; var doc = JsonDocument.Parse(@"{ ""Text"": ""1"", ""DetailChanges"":[{""Property"":""Comments"",""ChangedTo"":""2nd Comment"",""UniqueId"":null,""SummaryInstance"":null},{""Property"":""CCC"",""ChangedTo"":""XR71"",""UniqueId"":null,""SummaryInstance"":null}], ""Value"": 1, ""IsValid"": true, ""Account"" : { ""AccountId"" : 1234 } }" , options); Assert.IsNotNull(doc); var settings = new OperationSettings() { Name = "TestName" }; var instance = doc.RootElement.WalkStructure <CSharpClass, CSharpProperty> (new CSharpClass(settings, null), null); Assert.IsNotNull(instance); SettingsSingleton.Settings = new TempSettings() { Name = "ProcessCharpClass" }; Console.WriteLine(instance.ToString()); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); string str = File.ReadAllText(@"D:\Temp\CMCconverterTestJSON.txt"); //Console.WriteLine(str); JsonDocumentOptions options = new JsonDocumentOptions { AllowTrailingCommas = true }; string price = ""; using (JsonDocument document = JsonDocument.Parse(str, options)) { price = document.RootElement .GetProperty("data") .GetProperty("quote") .GetProperty("USD") .GetProperty("price") .ToString(); } double x = double.Parse(price); Console.WriteLine(x); Console.ReadKey(); }
/// <summary> /// Return a list of profiles for the Windows Terminal /// </summary> /// <param name="terminal">Windows Terminal package</param> /// <param name="settingsJson">Content of the settings JSON file of the Terminal</param> public static List <TerminalProfile> ParseSettings(TerminalPackage terminal, string settingsJson) { var profiles = new List <TerminalProfile>(); var options = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, }; var json = JsonDocument.Parse(settingsJson, options); json.RootElement.TryGetProperty("profiles", out JsonElement profilesElement); if (profilesElement.ValueKind != JsonValueKind.Object) { return(profiles); } profilesElement.TryGetProperty("list", out JsonElement profilesList); if (profilesList.ValueKind != JsonValueKind.Array) { return(profiles); } foreach (var profile in profilesList.EnumerateArray()) { profiles.Add(ParseProfile(terminal, profile)); } return(profiles); }
public AbpCliConfig Read(string directory) { var settingsFilePath = Path.Combine(directory, appSettingFileName); if (!File.Exists(settingsFilePath)) { throw new FileNotFoundException($"appsettings file could not be found. Path:{settingsFilePath}"); } var settingsFileContent = File.ReadAllText(settingsFilePath); var documentOptions = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip }; using (var document = JsonDocument.Parse(settingsFileContent, documentOptions)) { var element = document.RootElement.GetProperty("AbpCli"); var configText = element.GetRawText(); var options = new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() }, ReadCommentHandling = JsonCommentHandling.Skip }; return(JsonSerializer.Deserialize <AbpCliConfig>(configText, options)); } }
private IDictionary <string, string> ParseStream(Stream input, string password) { _data.Clear(); var jsonReaderOptions = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, }; byte[] buffer = new byte[input.Length]; input.Read(buffer, 0, buffer.Length); var passwordBytes = Encoding.ASCII.GetBytes(password); passwordBytes = SHA256.Create().ComputeHash(passwordBytes); var bytesDecrypted = AES.GetDecryptedByteArray(buffer, passwordBytes); var content = Encoding.GetEncoding("gb2312").GetString(bytesDecrypted); content = content.Replace("\0", ""); using (var doc = JsonDocument.Parse(content, jsonReaderOptions)) { if (doc.RootElement.ValueKind != JsonValueKind.Object) { throw new FormatException($"Unsupported JSON token '{doc.RootElement.ValueKind}' was found."); } VisitElement(doc.RootElement); } return(_data); }
public List <Item> AllItem() { List <Item> result = new List <Item>(); string itemsJson = JsonBody("http://localhost:8000/search"); //json parse var options = new JsonDocumentOptions { AllowTrailingCommas = true }; if (itemsJson != null) { using (JsonDocument document = JsonDocument.Parse(itemsJson, options)) { foreach (JsonElement element in document.RootElement.GetProperty("items").EnumerateArray()) { int id = element.GetProperty("id").GetInt32(); string name = element.GetProperty("name").GetString(); int price = element.GetProperty("price").GetInt32(); int current = element.GetProperty("current").GetInt32(); string category = element.GetProperty("category").GetString(); string image = element.GetProperty("image").GetString(); result.Add(new Item(id, name, price, current, category, image)); } } } return(result); }
public List <String> GetCategories() { List <string> result = new List <string>(); string itemsJson = JsonBody("http://localhost:8000/categories"); //json parse var options = new JsonDocumentOptions { AllowTrailingCommas = true }; if (itemsJson != null) { using (JsonDocument document = JsonDocument.Parse(itemsJson, options)) { foreach (JsonElement element in document.RootElement.GetProperty("categories").EnumerateArray()) { int id = element.GetProperty("id").GetInt32(); string name = element.GetProperty("name").GetString(); result.Add(name); } } } return(result); }
public static Tuple <double, DateTime> GetSingleExchangeRate(string firstCurrency, string secondCurrency, double amount = 1) { string fullJson = ApiConverterTool(firstCurrency, secondCurrency); if (string.IsNullOrEmpty(fullJson)) { throw new ArgumentNullException(); } JsonDocumentOptions options = new JsonDocumentOptions { AllowTrailingCommas = true }; string extractedPrice = ""; string extractedDate = ""; using (JsonDocument document = JsonDocument.Parse(fullJson, options)) { extractedPrice = document.RootElement .GetProperty("data") .GetProperty("quote") .GetProperty(secondCurrency) .GetProperty("price") .ToString(); extractedDate = document.RootElement .GetProperty("data") .GetProperty("quote") .GetProperty(secondCurrency) .GetProperty("last_updated") .ToString(); } Tuple <double, DateTime> result = new Tuple <double, DateTime>(double.Parse(extractedPrice), DateTime.Parse(extractedDate)); return(result); }
public dynamic Parse(string jsonStr = null) { JsonDocumentOptions jdo = new JsonDocumentOptions(); jdo.AllowTrailingCommas = true; jdo.CommentHandling = JsonCommentHandling.Skip; DynamicObjectExt result = new DynamicObjectExt(); foreach (string file in mJsonFiles) { using (StreamReader sr = new StreamReader(file, Encoding.UTF8)) { string content = sr.ReadToEnd(); JsonDocument doc = JsonDocument.Parse(content, jdo); JsonElement rootEl = doc.RootElement; BindConfigObject(result, rootEl); } } if (!string.IsNullOrEmpty(jsonStr)) { JsonDocument doc = JsonDocument.Parse(jsonStr, jdo); JsonElement rootEl = doc.RootElement; BindConfigObject(result, rootEl); } return(result); }
/// <inheritdoc/> public JsonDocument GetPayloadAsJson(JsonDocumentOptions documentOptions = default) { if (PostData == null) { return(null); } string content = PostData; if ("application/x-www-form-urlencoded".Equals(this.GetHeaderValue("content-type"), StringComparison.OrdinalIgnoreCase)) { var parsed = HttpUtility.ParseQueryString(PostData); var dictionary = new Dictionary <string, string>(); foreach (string key in parsed.Keys) { dictionary[key] = parsed[key]; } content = JsonSerializer.Serialize(dictionary); } if (content == null) { return(null); } return(JsonDocument.Parse(content, documentOptions)); }
public JsonSchemaSource Load(FileInfo path, string jsonPath) { var options = new JsonDocumentOptions { }; if (!m_cache.TryGetValue(path, out byte[] bytes))
private static double ComputeAverageTemperatures(string json) { JsonDocumentOptions options = new JsonDocumentOptions { AllowTrailingCommas = true }; using (JsonDocument document = JsonDocument.Parse(json, options)) { int sumOfAllTemperatures = 0; int count = 0; foreach (JsonElement element in document.RootElement.EnumerateArray()) { DateTimeOffset date = element.GetProperty("date").GetDateTimeOffset(); if (date.DayOfWeek == DayOfWeek.Monday) { int temp = element.GetProperty("temp").GetInt32(); sumOfAllTemperatures += temp; count++; } } double averageTemp = (double)sumOfAllTemperatures / count; return(averageTemp); } }
private IDictionary <string, string> ParseStream(int baseIndex, string json) { _baseIndex = baseIndex; // // Set up JSON options. // JsonDocumentOptions jsonDocumentOptions = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, }; // // Create a document and parse the JSON text. // using (JsonDocument doc = JsonDocument.Parse(json, jsonDocumentOptions)) { // // Only allow an object at the root of the document. // if (doc.RootElement.ValueKind != JsonValueKind.Object) { throw new FormatException("Invalid top level JSON object."); } // // Start parsing t the top level object. // this.VisitElement(doc.RootElement); } return(_data); }
public void FromJson() { var options = new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip, }; Aes128Ctr Load(string json) { using (JsonDocument doc = JsonDocument.Parse(json, options)) { return((Aes128Ctr)Aes128Ctr.FromJson(doc.RootElement)); } } Aes128Ctr cipher = Load(@"{ ""iv"": ""bc7f2ca23bfee0dd9725228ab2b0d98a"", }"); TestUtils.AssertBytesEqual( new byte[] { 0xbc, 0x7f, 0x2c, 0xa2, 0x3b, 0xfe, 0xe0, 0xdd, 0x97, 0x25, 0x22, 0x8a, 0xb2, 0xb0, 0xd9, 0x8a, }.ToImmutableArray(), cipher.Iv ); Assert.Throws <InvalidKeyJsonException>(() => Load(@"{ // ""iv"": ""..."", // lacks }") ); Assert.Throws <InvalidKeyJsonException>(() => Load(@"{ ""iv"": true, // not a string }") ); Assert.Throws <InvalidKeyJsonException>(() => Load(@"{ ""iv"": null, // not a string, but null }") ); Assert.Throws <InvalidKeyJsonException>(() => Load(@"{ ""iv"": ""not a hexadecimal string"", }") ); Assert.Throws <InvalidKeyJsonException>(() => Load(@"{ ""iv"": ""bc7f2ca23bfee0dd9725228ab2b0d98"", // iv: invalid length }") ); }
private static async Task <List <Setting> > FlattenJson(string filePath) { var flattenedJson = new List <Setting>(); var options = new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }; await using (FileStream fileStream = new FileStream( filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true)) using (JsonDocument document = await JsonDocument.ParseAsync(fileStream, options)) { foreach (JsonProperty property in document.RootElement.EnumerateObject()) { var keys = new List <string> { property.Name }; Parse(flattenedJson, keys, property); } } return(flattenedJson); }
public static ReportLayout ReadReportLayout(this PBIFile pbiFile) { var reportLayoutFile = pbiFile.ArchiveEntries .FirstOrDefault(x => x.FullName == PbiFileContents.ReportLayout); if (reportLayoutFile == null) { throw new ContentNotFoundException("Unable to read Report Layout content."); } var reader = new StreamReader(reportLayoutFile.Open(), Encoding.Unicode); var reportLayoutFileContent = reader.ReadToEnd(); if (reportLayoutFileContent == null) { throw new ContentEmptyException("Report Layout is empty"); } var options = new JsonDocumentOptions { AllowTrailingCommas = true }; var report = JsonDocument.Parse(reportLayoutFileContent, options); var reportLayout = new ReportLayout { Id = GetReportId(report.RootElement), ReportPages = GetPages(report.RootElement), Configuration = GetConfiguration(report.RootElement) }; return(reportLayout); }
/// <summary> /// Parses the Json body of a trigger call to a TriggerCall model object /// </summary> /// <param name="data">Json data</param> /// <param name="type">Trigger type</param> /// <returns>Parsed model object</returns> public static TriggerCall ParseJson(string data, string type) { TriggerCall tc = new TriggerCall(type); var options = new JsonDocumentOptions { AllowTrailingCommas = true }; using (JsonDocument document = JsonDocument.Parse(data, options)) { foreach (JsonProperty property in document.RootElement.EnumerateObject()) { if (property.Name.Equals("INPUT", System.StringComparison.CurrentCultureIgnoreCase)) { int length = property.Value.GetArrayLength(); tc.Input = new string[length]; for (int i = 0; i < length; i++) { tc.Input[i] = property.Value[i].ToString(); } } else { tc.EnvironmentVars.Add(property.Name, property.Value.GetString()); } } } return(tc); }
public async Task <ExportResult> ExportLocalizationFilesAsync(string templateJsonPath, ExportOptions options, CancellationToken cancellationToken = default) { JsonDocumentOptions jsonOptions = new JsonDocumentOptions() { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, }; try { using FileStream fileStream = new FileStream(templateJsonPath, FileMode.Open, FileAccess.Read); using JsonDocument jsonDocument = await JsonDocument.ParseAsync(fileStream, jsonOptions, cancellationToken).ConfigureAwait(false); TemplateStringExtractor stringExtractor = new TemplateStringExtractor(jsonDocument, _loggerFactory); IReadOnlyList <TemplateString> templateJsonStrings = stringExtractor.ExtractStrings(out string templateJsonLanguage); string targetDirectory = options.TargetDirectory ?? Path.Combine(Path.GetDirectoryName(templateJsonPath) ?? string.Empty, "localize"); await TemplateStringUpdater.UpdateStringsAsync( templateJsonStrings, templateJsonLanguage, options.Languages ?? ExportOptions.DefaultLanguages, targetDirectory, options.DryRun, _logger, cancellationToken).ConfigureAwait(false); return(new ExportResult(templateJsonPath)); } catch (Exception exception) { return(new ExportResult(templateJsonPath, null, exception)); } }
public object Parse(string json) { var jsonDocumentOptions = new JsonDocumentOptions(); var jsonDocument = JsonDocument.Parse(json, jsonDocumentOptions); return(_deserializer.Deserialize(jsonDocument.RootElement)); }
public static Object DeepParse(string json, JsonDocumentOptions options = default) { using (var doc = System.Text.Json.JsonDocument.Parse(json, options)) { return(DeepClone(doc)); } }
/// <summary> /// Loads the JSON data from a stream. /// </summary> /// <param name="stream">The JSON stream to read.</param> /// <param name="options">The parser options.</param> public static IDictionary <string, string> ParseStream(Stream stream, ParseToDictionaryOptions options = null) { var parserOptions = options ?? new ParseToDictionaryOptions(); var data = new SortedDictionary <string, string>(StringComparer.OrdinalIgnoreCase); var prefixStack = new Stack <string>(); var jsonDocumentOptions = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, }; if (parserOptions.Parents != null) { foreach (var parent in parserOptions.Parents) { prefixStack.Push(parent); } } using (var reader = new StreamReader(stream)) { using (var doc = JsonDocument.Parse(reader.ReadToEnd(), jsonDocumentOptions)) { if (doc.RootElement.ValueKind != JsonValueKind.Object) { throw new FormatException($"Top-level JSON element must be an object. Instead, '{doc.RootElement.ValueKind}' was found."); } VisitElement(doc.RootElement, prefixStack, data, parserOptions); } } return(data); }
/// <summary> /// Import games from the json file and add them to the global game dictionary. /// </summary> private static void ImportGames(ref int nGameCount) { var options = new JsonDocumentOptions { AllowTrailingCommas = true }; string strDocumentData = File.ReadAllText(GAME_JSON_FILE); if (strDocumentData == "") // File is empty { return; } using (JsonDocument document = JsonDocument.Parse(strDocumentData, options)) { JsonElement jArrGames; if (!document.RootElement.TryGetProperty(GAMES_ARRAY, out jArrGames)) { return; // 'games' array does not exist } foreach (JsonElement jElement in jArrGames.EnumerateArray()) { string strTitle = jElement.GetProperty(GAMES_ARRAY_TITLE).GetString(); string strLaunch = jElement.GetProperty(GAMES_ARRAY_LAUNCH).GetString(); string strPlatform = jElement.GetProperty(GAMES_ARRAY_PLATFORM).GetString(); bool bFavourite = jElement.GetProperty(GAMES_ARRAY_FAVOURITE).GetBoolean(); CGameData.AddGame(strTitle, strLaunch, bFavourite, strPlatform); nGameCount++; } } }
public static List <Field> GetJsonFields(string Json) { object obj = JsonSerializer.Deserialize <object>(Json); Console.WriteLine("JsonString:" + Json); Console.WriteLine("Obj:" + obj.ToString()); Console.WriteLine("ObjType:" + obj.GetType()); var options = new JsonDocumentOptions { AllowTrailingCommas = true }; var fields = new List <Field>(); using (JsonDocument document = JsonDocument.Parse(Json, options)) { fields = ReadProperties(document.RootElement).Distinct().Select(x => new Field() { FieldName = x.TrimStart('.') }).ToList(); } return(fields); }
public ModelQuery(string content) { _content = content; _parseOptions = new JsonDocumentOptions { AllowTrailingCommas = true }; }
public void RunJsonPatchTests(string path) { Debug.WriteLine($"Test {path}"); string text = System.IO.File.ReadAllText(path); var jsonOptions = new JsonDocumentOptions(); jsonOptions.CommentHandling = JsonCommentHandling.Skip; using JsonDocument doc = JsonDocument.Parse(text, jsonOptions); var testsEnumeratable = doc.RootElement.EnumerateArray(); var comparer = JsonElementEqualityComparer.Instance; foreach (var testGroup in testsEnumeratable) { JsonElement given = testGroup.GetProperty("given"); var testCases = testGroup.GetProperty("cases"); var testCasesEnumeratable = testCases.EnumerateArray(); foreach (var testCase in testCasesEnumeratable) { string comment; JsonElement commentElement; if (testCase.TryGetProperty("comment", out commentElement) && commentElement.ValueKind == JsonValueKind.String) { comment = commentElement.GetString(); } else { comment = ""; } try { JsonElement patch; Assert.IsTrue(testCase.TryGetProperty("patch", out patch) && patch.ValueKind == JsonValueKind.Array); JsonElement expected; if (testCase.TryGetProperty("error", out expected)) { // Assert.ThrowsException<JsonPatchParseException>(() => JsonPatch.Parse(exprElement.ToString())); } else if (testCase.TryGetProperty("result", out expected)) { using JsonDocument result = JsonPatch.ApplyPatch(given, patch); Assert.IsTrue(comparer.Equals(result.RootElement, expected)); using JsonDocument patch2 = JsonPatch.FromDiff(given, result.RootElement); using JsonDocument result2 = JsonPatch.ApplyPatch(given, patch2.RootElement); Assert.IsTrue(comparer.Equals(result2.RootElement, expected)); } } catch (Exception e) { Debug.WriteLine("File: {0}", path); Debug.WriteLine(comment); Debug.WriteLine("Error: {0}", e.Message); throw e; } } } }
private void LoadProgramSettingsJSON() { listaDirHistoria = new List <List <DirInfo> >(); try { string jsonString = File.ReadAllText(_settingsFileName); var options = new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }; using JsonDocument document = JsonDocument.Parse(jsonString, options); JsonElement element = document.RootElement.GetProperty("GUI"); this.StartPosition = FormStartPosition.Manual; this.DesktopLocation = new Point(element.GetProperty("Left").GetInt32(), element.GetProperty("Top").GetInt32()); this.ClientSize = new Size(element.GetProperty("Width").GetInt32(), element.GetProperty("Height").GetInt32()); element = document.RootElement.GetProperty("DirInfo"); DirInfo dir; int i = 0; foreach (JsonProperty Folder in element.EnumerateObject()) { listaDirHistoria.Add(new List <DirInfo>()); foreach (JsonElement SubFolder in Folder.Value.EnumerateArray()) { JsonElement SubF = SubFolder.EnumerateObject().ElementAt(0).Value; dir.Nombre = SubF.GetProperty("Name").GetString(); dir.Ruta = SubF.GetProperty("Path").GetString(); dir.Carpetas = SubF.GetProperty("Folders").GetInt32(); dir.Archivos = SubF.GetProperty("Files").GetInt32(); dir.porcentaje = SubF.GetProperty("Percentage").GetDouble(); dir.bytes = SubF.GetProperty("Bytes").GetInt64(); dir.kilo = SubF.GetProperty("KB").GetDouble(); dir.mega = SubF.GetProperty("MB").GetDouble(); dir.giga = SubF.GetProperty("GB").GetDouble(); listaDirHistoria[0].Add(dir); } i++; } } catch (FileNotFoundException) { } catch (Exception ex) { using (new CenterWinDialog(this)) { MessageBox.Show(this, "Error loading settings file\n\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
private JsonElement ToJsonDocument(string response) { var documentOptions = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip }; return(JsonDocument.Parse(response, documentOptions).RootElement); }
/// <summary> /// Parse text representing a single JSON value. /// </summary> /// <param name="utf8Json">JSON text to parse.</param> /// <param name="nodeOptions">Options to control the node behavior after parsing.</param> /// <param name="documentOptions">Options to control the document behavior during parsing.</param> /// <returns> /// A <see cref="JsonNode"/> representation of the JSON value. /// </returns> /// <exception cref="JsonException"> /// <paramref name="utf8Json"/> does not represent a valid single JSON value. /// </exception> public static JsonNode?Parse( ReadOnlySpan <byte> utf8Json, JsonNodeOptions?nodeOptions = null, JsonDocumentOptions documentOptions = default(JsonDocumentOptions)) { JsonElement element = JsonElement.ParseValue(utf8Json, documentOptions); return(JsonNodeConverter.Create(element, nodeOptions)); }
/// <summary> /// Initializes a new instance of the <see cref="PartImporter"/> class. /// </summary> /// <param name="repository">The repository.</param> /// <exception cref="ArgumentNullException">repository</exception> public PartImporter(ICadmusRepository repository) { _options = new JsonDocumentOptions { AllowTrailingCommas = true }; _repository = repository ?? throw new ArgumentNullException(nameof(repository)); }
public static JsonDocument ReadEmbeddedJsonFile(Assembly assembly, string path) { var options = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip }; var document = JsonDocument.Parse(ReadEmbeddedFile(assembly, path), options); return(document); }