private static void SerializeToJson(Stream stream, object value) { using var utf8JsonWriter = new Utf8JsonWriter(stream); JsonSerializer.Serialize(utf8JsonWriter, value); utf8JsonWriter.Flush(); }
/// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, MedicationDispense value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); }
public void ParseJson(bool compactData, TestCaseType type, string jsonString) { // Remove all formatting/indendation if (compactData) { using (JsonTextReader jsonReader = new JsonTextReader(new StringReader(jsonString))) { jsonReader.FloatParseHandling = FloatParseHandling.Decimal; JToken jtoken = JToken.ReadFrom(jsonReader); var stringWriter = new StringWriter(); using (JsonTextWriter jsonWriter = new JsonTextWriter(stringWriter)) { jtoken.WriteTo(jsonWriter); jsonString = stringWriter.ToString(); } } } byte[] dataUtf8 = Encoding.UTF8.GetBytes(jsonString); JsonObject obj = JsonObject.Parse(dataUtf8); var stream = new MemoryStream(dataUtf8); var streamReader = new StreamReader(stream, Encoding.UTF8, false, 1024, true); using (JsonTextReader jsonReader = new JsonTextReader(streamReader)) { JToken jtoken = JToken.ReadFrom(jsonReader); string expectedString = ""; string actualString = ""; if (type == TestCaseType.Json400KB) { expectedString = ReadJson400KB(jtoken); actualString = ReadJson400KB(obj); } else if (type == TestCaseType.HelloWorld) { expectedString = ReadHelloWorld(jtoken); actualString = ReadHelloWorld(obj); } Assert.Equal(expectedString, actualString); } string actual = obj.PrintJson(); // Change casing to match what JSON.NET does. actual = actual.Replace("true", "True").Replace("false", "False"); TextReader reader = new StringReader(jsonString); string expected = JsonTestHelper.NewtonsoftReturnStringHelper(reader); Assert.Equal(expected, actual); if (compactData) { var output = new ArrayFormatterWrapper(1024, SymbolTable.InvariantUtf8); var jsonUtf8 = new Utf8JsonWriter <ArrayFormatterWrapper>(output); jsonUtf8.Write(obj); jsonUtf8.Flush(); ArraySegment <byte> formatted = output.Formatted; string actualStr = Encoding.UTF8.GetString(formatted.Array, formatted.Offset, formatted.Count); Assert.Equal(jsonString, actualStr); } obj.Dispose(); }
/// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, GuidanceResponse value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); }
/// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, ResourceReference value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); }
private static void SerializeJsonIntoStream(Stream stream, object value) { using var utf8JsonWriter = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = false }); JsonSerializer.Serialize(utf8JsonWriter, value); utf8JsonWriter.Flush(); }
// Currently supports https://github.com/grafana/loki/blob/master/docs/api.md#post-lokiapiv1push public void Format(IEnumerable <LogEvent> logEvents, ITextFormatter formatter, TextWriter output) { if (logEvents == null) { throw new ArgumentNullException(nameof(logEvents)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } if (!logEvents.Any()) { return; } var timestampOverride = SystemClock.Instance.GetCurrentInstant(); // process labels for grouping/sorting var sortedStreams = logEvents .GroupBy(x => x.Properties .Where(prop => _labelNames.Contains(prop.Key)) .Select(prop => new KeyValuePair <string, string>(prop.Key, cleanseString(prop.Value.ToString()))) .Concat(_labelNames.Contains("level") ? new[] { new KeyValuePair <string, string>("level", GetLevel(x.Level)) } : new KeyValuePair <string, string>[] { }) .Concat(_globalLabels).ToHashSet(), new HashSetComparer()) .Select(stream => new KeyValuePair <HashSet <KeyValuePair <string, string> >, IOrderedEnumerable <LogEvent> >(stream.Key, stream.OrderBy(log => log.Timestamp))); var logLineBuffer = new ArrayBufferWriter <byte>(); using var logLineJsonWriter = new Utf8JsonWriter(logLineBuffer); var outputBuffer = new ArrayBufferWriter <byte>(); using var jsonWriter = new Utf8JsonWriter(outputBuffer); jsonWriter.WriteStartObject(); jsonWriter.WriteStartArray("streams"); foreach (var stream in sortedStreams) { jsonWriter.WriteStartObject(); jsonWriter.WriteStartObject("stream"); foreach (var label in stream.Key) { jsonWriter.WriteString(label.Key, label.Value); } jsonWriter.WriteEndObject(); jsonWriter.WriteStartArray("values"); foreach (var logEvent in stream.Value) { jsonWriter.WriteStartArray(); var timestamp = this._preserveTimestamps ? Instant.FromDateTimeOffset(logEvent.Timestamp) : timestampOverride; jsonWriter.WriteStringValue((timestamp.ToUnixTimeTicks() * 100).ToString()); // Construct a json object for the log line logLineJsonWriter.WriteStartObject(); logLineJsonWriter.WriteString("message", logEvent.RenderMessage()); foreach (var property in logEvent.Properties) { logLineJsonWriter.WriteString(property.Key, cleanseString(property.Value.ToString())); } if (this._preserveTimestamps == false) { logLineJsonWriter.WriteString("timestamp", Instant.FromDateTimeOffset(logEvent.Timestamp).ToString()); } if (logEvent.Exception != null) { var sb = new StringBuilder(); var e = logEvent.Exception; while (e != null) { sb.AppendLine(e.Message); sb.AppendLine(e.StackTrace); e = e.InnerException; } logLineJsonWriter.WriteString("exception", sb.ToString()); } logLineJsonWriter.WriteEndObject(); logLineJsonWriter.Flush(); jsonWriter.WriteStringValue(Encoding.UTF8.GetString(logLineBuffer.WrittenSpan)); jsonWriter.WriteEndArray(); logLineJsonWriter.Reset(); logLineBuffer.Clear(); } jsonWriter.WriteEndArray(); jsonWriter.WriteEndObject(); } jsonWriter.WriteEndArray(); jsonWriter.WriteEndObject(); jsonWriter.Flush(); output.Write(Encoding.UTF8.GetString(outputBuffer.WrittenSpan)); }
private MemoryStream WriteData(NotifyMessageItem[] list, IUserIdentity user) { bool haveValue = false; var jsonOptions = new JsonSerializerOptions(); jsonOptions.InitDefaults(new DBItemConverterFactory { CurrentUser = user, HttpJsonSettings = HttpJsonSettings.None, }); var stream = new MemoryStream(); //using (var streamWriter = new StreamWriter(stream, Encoding.UTF8, 80 * 1024, true)) using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Encoder = jsonOptions.Encoder, Indented = jsonOptions.WriteIndented })) { writer.WriteStartArray(); Type itemType = null; object id = null; foreach (var item in list) { if (item.Table.ItemType.Type != itemType) { if (itemType != null) { writer.WriteEndArray(); writer.WriteEndObject(); } itemType = item.Table.ItemType.Type; writer.WriteStartObject(); writer.WriteString("Type", itemType.Name); writer.WritePropertyName("Items"); writer.WriteStartArray(); } if (!item.ItemId.Equals(id) && (item.UserId != user.Id || item.Type == DBLogType.Delete)) { id = item.ItemId; writer.WriteStartObject(); writer.WriteNumber("Diff", (int)item.Type); writer.WriteNumber("User", item.UserId); writer.WriteString("Id", item.ItemId.ToString()); if (item.Type != DBLogType.Delete) { var value = item.Table.LoadItemById(item.ItemId); if (value != null && (value.Access?.GetFlag(AccessType.Read, user) ?? false) && value.PrimaryId != null) { writer.WritePropertyName("Value"); JsonSerializer.Serialize(writer, value, value.GetType(), jsonOptions); haveValue = true; } } else { haveValue = true; } writer.WriteEndObject(); } } writer.WriteEndArray(); writer.WriteEndObject(); writer.WriteEndArray(); writer.Flush(); } if (!haveValue) { stream.Dispose(); stream = null; } else { stream.Position = 0; } return(stream); }
/// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, CodeableConcept value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); }
/// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, EpisodeOfCare value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); }
/// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, AllergyIntolerance value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); }
/// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, ResearchSubject value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); }
public Stream GetSerializedContent() { writer.Flush(); stream.Position = 0; return(stream); }
/// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, MedicinalProductUndesirableEffect value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); }
public async Task ProcessRequestAsync(HttpContext context) { bool emptyBody = false; var jsonObjects = new Dictionary <string, object>(); try { using var document = await JsonDocument.ParseAsync(context.Request.Body); JsonElement root = document.RootElement; if (root.ValueKind == JsonValueKind.Object) { foreach (JsonProperty property in root.EnumerateObject()) { jsonObjects.Add(property.Name, property.Value.ToString()); } jsonObjects.Add("feedback", "your json has just gone through a native kestrel"); } else if (root.ValueKind == JsonValueKind.Array) { foreach (JsonElement element in root.EnumerateArray()) { } } } catch { emptyBody = true; } if (emptyBody) { jsonObjects.Add("firstname", "Natty"); jsonObjects.Add("lastname", "de Balancet"); jsonObjects.Add("info", "copy this json and post it back"); } var jsonWriterOptions = new JsonWriterOptions { Indented = true }; var memoryStream = new MemoryStream(); using (var utf8JsonWriter = new Utf8JsonWriter(memoryStream, jsonWriterOptions)) { utf8JsonWriter.WriteStartObject(); foreach (KeyValuePair <string, object> keyValuePair in jsonObjects) { utf8JsonWriter.WriteString(keyValuePair.Key, keyValuePair.Value.ToString()); } utf8JsonWriter.WriteEndObject(); utf8JsonWriter.Flush(); } context.Response.ContentLength = memoryStream.Length; context.Response.ContentType = "application/json"; memoryStream.Position = 0; await memoryStream.CopyToAsync(context.Response.Body); }
/// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, MeasureReport value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); }
public static byte[] SerializeToByteArray(StackItem item, uint maxSize) { using MemoryStream ms = new MemoryStream(); using Utf8JsonWriter writer = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = false, SkipValidation = false }); Stack stack = new Stack(); stack.Push(item); while (stack.Count > 0) { switch (stack.Pop()) { case Array array: writer.WriteStartArray(); stack.Push(JsonTokenType.EndArray); for (int i = array.Count - 1; i >= 0; i--) { stack.Push(array[i]); } break; case JsonTokenType.EndArray: writer.WriteEndArray(); break; case ByteString buffer: writer.WriteStringValue(Convert.ToBase64String(buffer.GetSpan())); break; case Integer num: { var integer = num.GetBigInteger(); if (integer > JNumber.MAX_SAFE_INTEGER || integer < JNumber.MIN_SAFE_INTEGER) { throw new InvalidOperationException(); } writer.WriteNumberValue((double)num.GetBigInteger()); break; } case Boolean boolean: writer.WriteBooleanValue(boolean.ToBoolean()); break; case Map map: writer.WriteStartObject(); stack.Push(JsonTokenType.EndObject); foreach (var pair in map.Reverse()) { stack.Push(pair.Value); stack.Push(pair.Key); stack.Push(JsonTokenType.PropertyName); } break; case JsonTokenType.EndObject: writer.WriteEndObject(); break; case JsonTokenType.PropertyName: writer.WritePropertyName(((PrimitiveType)stack.Pop()).GetSpan()); break; case Null _: writer.WriteNullValue(); break; default: throw new InvalidOperationException(); } if (ms.Position > maxSize) { throw new InvalidOperationException(); } } writer.Flush(); if (ms.Position > maxSize) { throw new InvalidOperationException(); } return(ms.ToArray()); }
/// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, DeviceRequest value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); }
public override string ToString() { using (var ms = new MemoryStream()) using (var jw = new Utf8JsonWriter(ms)) { jw.WriteStartObject(); { if (Text != null) { jw.WriteString("text", Text); } if (Heading != null) { jw.WriteString("heading", Heading); } switch (Transition) { case ToastTransition.Fade: jw.WriteString("showHideTransition", "fade"); break; case ToastTransition.Slide: jw.WriteString("showHideTransition", "slide"); break; case ToastTransition.Plain: jw.WriteString("showHideTransition", "plain"); break; } if (AllowToastClose != null) { jw.WriteBoolean("allowToastClose", AllowToastClose.Value); } if (HideAfter > TimeSpan.Zero) { jw.WriteNumber("hideAfter", HideAfter.TotalMilliseconds); } else if (HideAfter < TimeSpan.Zero) { jw.WriteBoolean("hideAfter", false); } if (StackLength > 0) { jw.WriteNumber("stack", StackLength); } else if (StackLength < 0) { jw.WriteBoolean("stack", false); } var p = Position; if (!p.IsEmpty) { jw.WritePropertyName("position"); p.WriteTo(jw); } switch (Icon) { case ToastIcon.Warning: jw.WriteString("icon", "warning"); break; case ToastIcon.Success: jw.WriteString("icon", "success"); break; case ToastIcon.Error: jw.WriteString("icon", "error"); break; case ToastIcon.Information: jw.WriteString("icon", "information"); break; } switch (TextAlign) { case TextAlignment.Left: jw.WriteString("textAlign", "left"); break; case TextAlignment.Center: jw.WriteString("textAlign", "center"); break; case TextAlignment.Right: jw.WriteString("textAlign", "right"); break; } if (ShowLoader != null) { jw.WriteBoolean("loader", ShowLoader.Value); } if (LoaderBackground != null) { jw.WriteString("loaderBg", LoaderBackground); } } jw.WriteEndObject(); jw.Flush(); return(Encoding.UTF8.GetString(ms.ToArray())); } }
private static void ProcessFile(string arg) { FileInfo fi = new FileInfo(arg); if (fi.Length < 4 || !IsRegistryFile(arg)) { return; } byte[] raw = File.ReadAllBytes(arg); RegistryHive reg = new RegistryHive(raw, arg) { RecoverDeleted = true, FlushRecordListsAfterParse = false }; string name; using (FileStream fs = new FileStream(arg, FileMode.Open, FileAccess.Read)) { name = Hashes.CalculateMD5FromStream(fs); } string path = $"regdrop/{name}"; Directory.CreateDirectory(path); File.WriteAllText($"{path}/info.txt", reg.Header.ToString()); if (!reg.Header.ValidateCheckSum()) { Console.Error.WriteLine("Checksum validation error. Exiting."); return; } if (reg.Header.PrimarySequenceNumber != reg.Header.SecondarySequenceNumber) { string filePath = Path.GetDirectoryName(arg); string fileName = Path.GetFileNameWithoutExtension(arg); var logFiles = Directory.GetFiles(filePath, $"{fileName}.LOG?"); if (logFiles.Length == 0) { Console.Error.WriteLine($"[{arg}] Transaction logs missing. Exiting."); return; } else { reg.ProcessTransactionLogs(logFiles.ToList(), true); } } reg.ParseHive(); string dumpFilePathTmp = $"{path}/dump.tmp"; reg.ExportDataToCommonFormat(dumpFilePathTmp, false); string dumpFilePathCsv = $"{path}/dump.csv"; string dumpFilePathJson = $"{path}/dump.json"; using (DataTable dt = new DataTable()) { dt.Columns.Add("type", typeof(string)); dt.Columns.Add("active", typeof(string)); dt.Columns.Add("offset", typeof(decimal)); dt.Columns.Add("path", typeof(string)); dt.Columns.Add("name", typeof(string)); dt.Columns.Add("dataType", typeof(decimal)); dt.Columns.Add("value", typeof(string)); dt.Columns.Add("lastWriteTime", typeof(string)); using (var fs = new FileStream(dumpFilePathTmp, FileMode.Open, FileAccess.Read, FileShare.Read)) { dt.FromCsv(fs, false); } DataColumn type = dt.Columns["type"]; foreach (var dr in dt.Rows .OfType <DataRow>() .Where(x => (string)x[type] == "value")) { DataColumn dataType = dt.Columns["dataType"]; DataColumn value = dt.Columns["value"]; byte[] data = ConvertToBytes((string)dr[value]); decimal dataTypeVal = (decimal)dr[dataType]; if (dataTypeVal == 0x2) { string txt = Encoding.Unicode.GetString(data).TrimEnd('\0'); dr[value] = txt; } else if (dataTypeVal == 0x4 && data.Length == 4) { int val = BitConverter.ToInt32(data); dr[value] = val.ToString(); } else if (dataTypeVal == 0x5 && data.Length == 4) { int val = BitConverter.ToInt32(data.Reverse().ToArray()); dr[value] = val.ToString(); } else if (dataTypeVal == 0x7) { string txtlist = Encoding.Unicode.GetString(data).TrimEnd('\0'); string[] split = txtlist.Split('\0', StringSplitOptions.RemoveEmptyEntries); dr[value] = string.Join("\n", split); } else if (dataTypeVal == 0xb && data.Length == 8) { long val = BitConverter.ToInt64(data); dr[value] = val.ToString(); } else { dr[value] = Convert.ToBase64String(data); } } using (var fs = new FileStream(dumpFilePathCsv, FileMode.Create, FileAccess.Write, FileShare.Read)) { dt.ToCsv(fs); } JsonDocument jdoc; dt.ToJson(out jdoc); using (var fs = new FileStream(dumpFilePathJson, FileMode.Create, FileAccess.Write, FileShare.Read)) { Utf8JsonWriter writer = new Utf8JsonWriter(fs); jdoc.WriteTo(writer); writer.Flush(); } } if (File.Exists(dumpFilePathTmp)) { File.Delete(dumpFilePathTmp); } }
private void LogJson <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter, LogFormat jsonFormat = LogFormat.NewlineDelimitedJson) { Stream outputStream = _outputStream; if (jsonFormat == LogFormat.JsonSequence) { outputStream.WriteByte(JsonSequenceRecordSeparator); } //CONSIDER Should we cache up the loggers and writers? using (var jsonWriter = new Utf8JsonWriter(outputStream, new JsonWriterOptions { Indented = false })) { // Matches the format of JsonConsoleFormatter jsonWriter.WriteStartObject(); jsonWriter.WriteString("Timestamp", (state is IStateWithTimestamp stateWithTimestamp) ? FormatTimestamp(stateWithTimestamp) : string.Empty); jsonWriter.WriteString("LogLevel", logLevel.ToString()); jsonWriter.WriteNumber("EventId", eventId.Id); // EventId.Name is optional; use empty string if it is null as this // works better with analytic platforms such as Azure Monitor. jsonWriter.WriteString("EventName", eventId.Name ?? string.Empty); jsonWriter.WriteString("Category", _categoryName); jsonWriter.WriteString("Message", formatter(state, exception)); if (exception != null) { jsonWriter.WriteString("Exception", exception.ToString()); } // Write out state if (state is IEnumerable <KeyValuePair <string, object> > values) { jsonWriter.WriteStartObject("State"); jsonWriter.WriteString("Message", state.ToString()); foreach (KeyValuePair <string, object> arg in values) { WriteKeyValuePair(jsonWriter, arg); } jsonWriter.WriteEndObject(); } // Write out scopes if (_scopes.HasScopes) { jsonWriter.WriteStartArray("Scopes"); foreach (IReadOnlyList <KeyValuePair <string, object> > scope in _scopes) { jsonWriter.WriteStartObject(); foreach (KeyValuePair <string, object> scopeValue in scope) { WriteKeyValuePair(jsonWriter, scopeValue); } jsonWriter.WriteEndObject(); } jsonWriter.WriteEndArray(); } jsonWriter.WriteEndObject(); jsonWriter.Flush(); } // JSON Sequence and NDJson both use newline as the end character outputStream.WriteByte((byte)'\n'); outputStream.Flush(); }
public async Task <Unit> Handle(SaveSettingsCommand request, CancellationToken cancellationToken) { var leagueHasChanged = request.Settings.LeagueId != settings.LeagueId; var languageHasChanged = request.Settings.Language_Parser != settings.Language_Parser; if (settings.Language_UI != request.Settings.Language_UI) { await mediator.Send(new SetUiLanguageCommand(request.Settings.Language_UI)); } if (settings.Language_Parser != request.Settings.Language_Parser) { await mediator.Send(new SetGameLanguageCommand(request.Settings.Language_Parser)); } request.Settings.CopyValuesTo(settings); var json = JsonSerializer.Serialize(settings); var defaults = JsonSerializer.Serialize(new SidekickSettings()); var filePath = SidekickPaths.GetDataFilePath(FileName); using var fileStream = File.Create(filePath); using var writer = new Utf8JsonWriter(fileStream, options: new JsonWriterOptions { Indented = true }); using var document = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip }); using var defaultsDocument = JsonDocument.Parse(defaults, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip }); var root = document.RootElement; var defaultsRoot = defaultsDocument.RootElement; if (root.ValueKind == JsonValueKind.Object) { writer.WriteStartObject(); } else { return(Unit.Value); } foreach (var property in root.EnumerateObject()) { if (defaultsRoot.GetProperty(property.Name).ToString() == property.Value.ToString()) { continue; } property.WriteTo(writer); } writer.WriteEndObject(); writer.Flush(); if (writer.BytesCommitted == 0) { File.Delete(filePath); } if (!request.SkipInitialize && (languageHasChanged || leagueHasChanged)) { await mediator.Send(new ClearCacheCommand()); await mediator.Send(new InitializeCommand(false, false)); } return(Unit.Value); }
public override byte[] Serialize(IDictionary <string, object> values) { if (values == null || values.Count == 0) { return(Array.Empty <byte>()); } using (var bufferWriter = new ArrayBufferWriter <byte>()) { using var writer = new Utf8JsonWriter(bufferWriter); writer.WriteStartObject(); foreach (var(key, value) in values) { if (value == null) { writer.WriteNull(key); continue; } // We want to allow only simple types to be serialized. if (!CanSerializeType(value.GetType())) { throw new InvalidOperationException( Resources.FormatTempData_CannotSerializeType( typeof(DefaultTempDataSerializer).FullName, value.GetType())); } switch (value) { case Enum _: writer.WriteNumber(key, (int)value); break; case string stringValue: writer.WriteString(key, stringValue); break; case int intValue: writer.WriteNumber(key, intValue); break; case bool boolValue: writer.WriteBoolean(key, boolValue); break; case DateTime dateTime: writer.WriteString(key, dateTime.ToString("r", CultureInfo.InvariantCulture)); break; case Guid guid: writer.WriteString(key, guid.ToString("B", CultureInfo.InvariantCulture)); break; } } writer.WriteEndObject(); writer.Flush(); return(bufferWriter.WrittenMemory.ToArray()); } }
private static byte[] LoadEnusLocalizedStringData() { using MemoryStream memoryStream = new MemoryStream(); using Utf8JsonWriter writer = new Utf8JsonWriter(memoryStream); writer.WriteStartObject(); writer.WriteStartObject("meta"); writer.WriteString("locale", "enus"); writer.WriteEndObject(); // meta writer.WriteStartObject("gamestrings"); writer.WriteStartObject("abiltalent"); writer.WriteStartObject("cooldown"); writer.WriteString("AlarakDiscordStrike|AlarakDiscordStrike|Q|False", "Cooldown: 8 seconds"); writer.WriteEndObject(); writer.WriteStartObject("energy"); writer.WriteString("AlarakDiscordStrike|AlarakDiscordStrike|Q|False", "<s val=\"bfd4fd\" name=\"StandardTooltipDetails\">Mana: 55</s>"); writer.WriteEndObject(); writer.WriteStartObject("full"); writer.WriteString("AlarakDiscordStrike|AlarakDiscordStrike|Q|False", "After a <c val=\"bfd4fd\">0.5</c> second delay, enemies in front of Alarak take <c val=\"bfd4fd\">175~~0.04~~</c> damage and are silenced for <c val=\"bfd4fd\">1.5</c> seconds. "); writer.WriteEndObject(); writer.WriteStartObject("life"); writer.WriteString("AlarakDiscordStrike|AlarakDiscordStrike|Q|False", "No life"); writer.WriteEndObject(); writer.WriteStartObject("name"); writer.WriteString("AlarakDiscordStrike|AlarakDiscordStrike|Q|False", "Discord Strike"); writer.WriteEndObject(); writer.WriteStartObject("short"); writer.WriteString("AlarakDiscordStrike|AlarakDiscordStrike|Q|False", "Damage and silence enemies in an area"); writer.WriteString("ZuljinWrongPlaceWrongTime|ZuljinWrongPlaceWrongTime|W|False", "Bonus Twin Cleave damage at apex"); writer.WriteEndObject(); writer.WriteEndObject(); // end abiltalent writer.WriteStartObject("unit"); writer.WriteStartObject("difficulty"); writer.WriteString("Alarak", "Hard"); writer.WriteEndObject(); writer.WriteStartObject("expandedrole"); writer.WriteString("Alarak", "Melee Assassin"); writer.WriteEndObject(); writer.WriteStartObject("role"); writer.WriteString("Alarak", "Assassin,Warrior"); writer.WriteEndObject(); writer.WriteStartObject("searchtext"); writer.WriteString("Alarak", "Alarak Ascendant Protoss SC SC2 StarCraft Star2 Starcraft2 II 2 Legacy of the Void LotV Covert Ops CO"); writer.WriteEndObject(); writer.WriteStartObject("title"); writer.WriteString("Alarak", "Highlord of the Tal'darim"); writer.WriteEndObject(); writer.WriteStartObject("type"); writer.WriteString("Alarak", "Melee"); writer.WriteEndObject(); writer.WriteEndObject(); // unit writer.WriteEndObject(); // gamestrings writer.WriteEndObject(); writer.Flush(); return(memoryStream.ToArray()); }
/// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, MessageHeader value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); }
private void ConvertFile(string filePath) { Dictionary <string, Dictionary <string, Dictionary <string, string> > > groupedItems = new Dictionary <string, Dictionary <string, Dictionary <string, string> > >(); string?fileNameNoExt = Path.GetFileNameWithoutExtension(filePath); if (string.IsNullOrEmpty(fileNameNoExt)) { return; } ReadOnlySpan <char> versionSpan = string.Empty; ReadOnlySpan <char> localeSpan = string.Empty; int firstSplit = fileNameNoExt.IndexOf('_', StringComparison.OrdinalIgnoreCase); int lastSplit = fileNameNoExt.LastIndexOf('_'); if (firstSplit > -1 && lastSplit > -1) { localeSpan = fileNameNoExt.AsSpan(lastSplit + 1); if (firstSplit - lastSplit < 0) { versionSpan = fileNameNoExt.AsSpan(firstSplit + 1, lastSplit - firstSplit - 1); } } Directory.CreateDirectory(_outputDirectory); using FileStream fileStream = new FileStream(Path.Combine(_outputDirectory, $"{fileNameNoExt}.json"), FileMode.Create); using Utf8JsonWriter utf8JsonWriter = new Utf8JsonWriter(fileStream, new JsonWriterOptions { Indented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); utf8JsonWriter.WriteStartObject(); utf8JsonWriter.WriteStartObject("meta"); utf8JsonWriter.WriteString("version", versionSpan); utf8JsonWriter.WriteString("locale", localeSpan); utf8JsonWriter.WriteEndObject(); utf8JsonWriter.WriteStartObject("gamestrings"); using StreamReader reader = File.OpenText(filePath); while (!reader.EndOfStream) { string?line = reader.ReadLine(); if (line is null) { continue; } string[] idAndValue = line.Split('=', 2, StringSplitOptions.RemoveEmptyEntries); string[] idParts = idAndValue[0].Split('/', 3, StringSplitOptions.RemoveEmptyEntries); if (groupedItems.TryGetValue(idParts[0], out Dictionary <string, Dictionary <string, string> >?value)) { if (value.TryGetValue(idParts[1], out Dictionary <string, string>?valueInner)) { valueInner.TryAdd(idParts[2], idAndValue[1]); } else { value.Add(idParts[1], new Dictionary <string, string>() { { idParts[2], idAndValue[1] }, }); } } else { groupedItems.Add(idParts[0], new Dictionary <string, Dictionary <string, string> >() { { idParts[1], new Dictionary <string, string>() { { idParts[2], idAndValue[1] }, } }, }); } } foreach (KeyValuePair <string, Dictionary <string, Dictionary <string, string> > > firstKey in groupedItems) { utf8JsonWriter.WriteStartObject(firstKey.Key); foreach (KeyValuePair <string, Dictionary <string, string> > secondKey in firstKey.Value) { utf8JsonWriter.WriteStartObject(secondKey.Key); foreach (KeyValuePair <string, string> thirdKey in secondKey.Value) { utf8JsonWriter.WriteString(thirdKey.Key, thirdKey.Value); } utf8JsonWriter.WriteEndObject(); } utf8JsonWriter.WriteEndObject(); } utf8JsonWriter.WriteEndObject(); // end meta utf8JsonWriter.WriteEndObject(); utf8JsonWriter.Flush(); }
/// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, BiologicallyDerivedProduct value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); }
internal void Serialize(IQueryResult result, IBufferWriter <byte> writer) { using var jsonWriter = new Utf8JsonWriter(writer, _options); WriteResult(jsonWriter, result); jsonWriter.Flush(); }
/// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, Annotation value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); }
/// <summary> /// Writes a specified value as JSON. /// </summary> public override void Write(Utf8JsonWriter writer, ProdCharacteristic value, JsonSerializerOptions options) { value.SerializeJson(writer, options, true); writer.Flush(); }