public override IMessageBase[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { List <MessageBase> result = new List <MessageBase>(); while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) { JsonElement data = JsonSerializer.Deserialize <JsonElement>(ref reader, options); result.Add(data.GetProperty("type").GetString() switch { SourceMessage.MsgType => Utils.Deserialize <SourceMessage>(in data, options), QuoteMessage.MsgType => Utils.Deserialize <QuoteMessage>(in data, options), PlainMessage.MsgType => Utils.Deserialize <PlainMessage>(in data, options), ImageMessage.MsgType => Utils.Deserialize <ImageMessage>(in data, options), FlashImageMessage.MsgType => Utils.Deserialize <FlashImageMessage>(in data, options), AtMessage.MsgType => Utils.Deserialize <AtMessage>(in data, options), AtAllMessage.MsgType => Utils.Deserialize <AtAllMessage>(in data, options), FaceMessage.MsgType => Utils.Deserialize <FaceMessage>(in data, options), XmlMessage.MsgType => Utils.Deserialize <XmlMessage>(in data, options), JsonMessage.MsgType => Utils.Deserialize <JsonMessage>(in data, options), AppMessage.MsgType => Utils.Deserialize <AppMessage>(in data, options), PokeMessage.MsgType => Utils.Deserialize <PokeMessage>(in data, options), VoiceMessage.MsgType => Utils.Deserialize <VoiceMessage>(in data, options), UnknownMessage.MsgType => Utils.Deserialize <UnknownMessage>(in data, options), _ => default });
public override void Write(Utf8JsonWriter writer, ApiManagementSubscriptionUpdatedEventData model, JsonSerializerOptions options) { throw new NotImplementedException(); }
/// <summary> /// Deserialize JSON into a FHIR Bundle#Response /// </summary> public static void DeserializeJson(this Bundle.ResponseComponent current, ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); if (Hl7.Fhir.Serialization.FhirSerializerOptions.Debug) { Console.WriteLine($"Bundle.ResponseComponent >>> Bundle#Response.{propertyName}, depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } reader.Read(); current.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException($"Bundle.ResponseComponent: invalid state! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); }
public override MetastoreRegistrationResponse Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using var document = JsonDocument.ParseValue(ref reader); return(DeserializeMetastoreRegistrationResponse(document.RootElement)); }
public override SalesforceMarketingCloudSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using var document = JsonDocument.ParseValue(ref reader); return(DeserializeSalesforceMarketingCloudSource(document.RootElement)); }
public override void Write(Utf8JsonWriter writer, SapTableSource model, JsonSerializerOptions options) { writer.WriteObjectValue(model); }
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { var stringValue = ToShortDateString(value); writer.WriteStringValue(stringValue); }
public override ImageInfo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null || reader.TokenType == JsonTokenType.None) { return(null !); } if (reader.TokenType != JsonTokenType.StartObject) { throw new InvalidOperationException("Expected object."); } int width = default; int height = default; int xResolution = default; int yResolution = default; var iptc = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); var exif = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); reader.ReadOrFail(); while (reader.TokenType != JsonTokenType.EndObject) { if (reader.TokenType != JsonTokenType.PropertyName) { throw new InvalidOperationException("Expected property."); } if (reader.ValueTextEquals("width") || reader.ValueTextEquals("Width")) { reader.ReadOrFail(); width = reader.GetInt32(); reader.ReadOrFail(); } else if (reader.ValueTextEquals("height") || reader.ValueTextEquals("Height")) { reader.ReadOrFail(); height = reader.GetInt32(); reader.ReadOrFail(); } else if (reader.ValueTextEquals("xResolution") || reader.ValueTextEquals("XResolution")) { reader.ReadOrFail(); xResolution = reader.GetInt32(); reader.ReadOrFail(); } else if (reader.ValueTextEquals("yResolution") || reader.ValueTextEquals("YResolution")) { reader.ReadOrFail(); yResolution = reader.GetInt32(); reader.ReadOrFail(); } else if (reader.ValueTextEquals("iptc") || reader.ValueTextEquals("Iptc")) { reader.ReadOrFail(); if (reader.TokenType != JsonTokenType.StartObject) { throw new InvalidOperationException("Expected object."); } reader.ReadOrFail(); while (JsonTokenType.EndObject != reader.TokenType) { if (reader.TokenType != JsonTokenType.PropertyName) { throw new InvalidOperationException("Expected property."); } var key = reader.GetString(); reader.ReadOrFail(); var value = reader.GetString(); iptc[key] = value; reader.ReadOrFail(); } reader.ReadOrFail(); } else if (reader.ValueTextEquals("exif") || reader.ValueTextEquals("Exif")) { reader.ReadOrFail(); if (reader.TokenType != JsonTokenType.StartObject) { throw new InvalidOperationException("Expected object."); } reader.ReadOrFail(); while (JsonTokenType.EndObject != reader.TokenType) { if (reader.TokenType != JsonTokenType.PropertyName) { throw new InvalidOperationException("Expected property."); } var key = reader.GetString(); reader.ReadOrFail(); var value = reader.GetString(); exif[key] = value; reader.ReadOrFail(); } reader.ReadOrFail(); } else { reader.ReadOrFail(); reader.Skip(); reader.ReadOrFail(); } } reader.Read(); return(new ImageInfo(width, height, xResolution, yResolution, iptc, exif)); }
protected override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IEnumerator <TElement> enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return(true); } } else { Debug.Assert(state.Current.CollectionEnumerator is IEnumerator <TElement>); enumerator = (IEnumerator <TElement>)state.Current.CollectionEnumerator; } JsonConverter <TElement> converter = GetElementConverter(ref state); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return(false); } TElement element = enumerator.Current; if (!converter.TryWrite(writer, element, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return(false); } } while (enumerator.MoveNext()); return(true); }
public override void Write(Utf8JsonWriter writer, DefaultKeyword value, JsonSerializerOptions options) { writer.WritePropertyName(DefaultKeyword.Name); value.Value.WriteTo(writer); }
public override void Write(Utf8JsonWriter writer, ImageInfo value, JsonSerializerOptions options) { throw new InvalidOperationException($"{nameof(ImageInfoConverter)} not supposed to be used to serialize image info."); }
public override DefaultKeyword Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var element = JsonDocument.ParseValue(ref reader).RootElement; return(new DefaultKeyword(element)); }
public override void Write(Utf8JsonWriter writer, IDictionary <TKey, TValue> value, JsonSerializerOptions options) { var convertedDictionary = new Dictionary <string?, TValue>(value.Count); foreach (var(k, v) in value) { convertedDictionary[k?.ToString()] = v; } JsonSerializer.Serialize(writer, convertedDictionary, options); convertedDictionary.Clear(); }
public override IDictionary <TKey, TValue> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var convertedType = typeof(Dictionary <,>) .MakeGenericType(typeof(string), typeToConvert.GenericTypeArguments[1]); var value = JsonSerializer.Deserialize(ref reader, convertedType, options); var instance = (Dictionary <TKey, TValue>)Activator.CreateInstance( typeToConvert, BindingFlags.Instance | BindingFlags.Public, null, null, CultureInfo.CurrentCulture); var enumerator = (IEnumerator)convertedType.GetMethod("GetEnumerator") !.Invoke(value, null); var parse = typeof(TKey).GetMethod("Parse", 0, BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Any, new[] { typeof(string) }, null); if (parse == null) { throw new NotSupportedException($"{typeof(TKey)} as TKey in IDictionary<TKey, TValue> is not supported."); } while (enumerator.MoveNext()) { var element = (KeyValuePair <string?, TValue>)enumerator.Current; instance.Add((TKey)parse.Invoke(null, new[] { element.Key }), element.Value); } return(instance); }
public override AcsChatEventInThreadBaseProperties Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using var document = JsonDocument.ParseValue(ref reader); return(DeserializeAcsChatEventInThreadBaseProperties(document.RootElement)); }
public override Nullable <RecurrenceType> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) { return(null); } if (reader.TokenType == JsonTokenType.String) { var str = reader.GetString(); if (Enum.TryParse(typeof(RecurrenceType), str, true, out var rt)) { return((Nullable <RecurrenceType>)rt); } } if (reader.TokenType == JsonTokenType.Number) { try { return((Nullable <RecurrenceType>)Enum.ToObject(typeof(RecurrenceType), reader.GetInt32())); } catch { } } return(null); }
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString()); }
public override void Write(Utf8JsonWriter writer, Nullable <RecurrenceType> value, JsonSerializerOptions options) { if (value.HasValue) { writer.WriteStringValue(value.Value.ToString()); } else { writer.WriteNullValue(); } }
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var stringValue = reader.GetString(); return(FromShortDateString(stringValue)); }
/// <summary>Reads and converts the JSON to <see cref="AsteroidField"/>.</summary> /// <param name="reader">The reader.</param> /// <param name="typeToConvert">The type to convert.</param> /// <param name="options">An object that specifies serialization options to use.</param> /// <returns>The converted value.</returns> public override AsteroidField?Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType != JsonTokenType.StartObject || !reader.Read() || reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } var prop = reader.GetString(); if (!string.Equals( prop, "id", options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { throw new JsonException(); } if (!reader.Read() || reader.TokenType != JsonTokenType.String) { throw new JsonException(); } var id = reader.GetString(); if (id is null) { throw new JsonException(); } if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } prop = reader.GetString(); if (!string.Equals( prop, nameof(IIdItem.IdItemTypeName), options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { throw new JsonException(); } if (!reader.Read() || reader.TokenType != JsonTokenType.String) { throw new JsonException(); } var idItemTypeName = reader.GetString(); if (string.IsNullOrEmpty(idItemTypeName) || !string.Equals(idItemTypeName, AsteroidField.AsteroidFieldIdItemTypeName)) { throw new JsonException(); } if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } prop = reader.GetString(); if (!string.Equals( prop, "seed", options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { throw new JsonException(); } if (!reader.Read() || !reader.TryGetUInt32(out var seed)) { throw new JsonException(); } if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } prop = reader.GetString(); if (!string.Equals( prop, nameof(CosmicLocation.StructureType), options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { throw new JsonException(); } if (!reader.Read() || !reader.TryGetInt32(out var structureTypeInt) || !Enum.IsDefined(typeof(CosmicStructureType), structureTypeInt)) { throw new JsonException(); } var structureType = (CosmicStructureType)structureTypeInt; if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } prop = reader.GetString(); if (!string.Equals( prop, nameof(Location.ParentId), options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { throw new JsonException(); } if (!reader.Read()) { throw new JsonException(); } var parentId = reader.GetString(); if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } prop = reader.GetString(); if (!string.Equals( prop, nameof(Location.AbsolutePosition), options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { throw new JsonException(); } if (!reader.Read()) { throw new JsonException(); } Vector3 <HugeNumber>[]? absolutePosition; if (reader.TokenType == JsonTokenType.Null) { absolutePosition = null; } else { var vectorArrayConverter = (JsonConverter <Vector3 <HugeNumber>[]>)options.GetConverter(typeof(Vector3 <HugeNumber>[])); absolutePosition = vectorArrayConverter.Read(ref reader, typeof(Vector3 <HugeNumber>[]), options); } if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } prop = reader.GetString(); if (!string.Equals( prop, nameof(CosmicLocation.Name), options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { throw new JsonException(); } if (!reader.Read()) { throw new JsonException(); } var name = reader.GetString(); if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } prop = reader.GetString(); if (!string.Equals( prop, nameof(CosmicLocation.Velocity), options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { throw new JsonException(); } if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject) { throw new JsonException(); } var velocity = JsonSerializer.Deserialize <Vector3 <HugeNumber> >(ref reader, options); if (reader.TokenType != JsonTokenType.EndObject) { throw new JsonException(); } if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } prop = reader.GetString(); if (!string.Equals( prop, nameof(CosmicLocation.Orbit), options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { throw new JsonException(); } if (!reader.Read()) { throw new JsonException(); } Orbit?orbit; if (reader.TokenType == JsonTokenType.Null) { orbit = null; } else { if (reader.TokenType != JsonTokenType.StartObject) { throw new JsonException(); } else { orbit = JsonSerializer.Deserialize <Orbit>(ref reader, options); } if (reader.TokenType != JsonTokenType.EndObject) { throw new JsonException(); } } if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } prop = reader.GetString(); if (!string.Equals( prop, nameof(Location.Position), options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { throw new JsonException(); } if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject) { throw new JsonException(); } var position = JsonSerializer.Deserialize <Vector3 <HugeNumber> >(ref reader, options); if (reader.TokenType != JsonTokenType.EndObject) { throw new JsonException(); } if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } prop = reader.GetString(); if (!string.Equals( prop, nameof(CosmicLocation.Temperature), options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { throw new JsonException(); } if (!reader.Read()) { throw new JsonException(); } double?temperature; if (reader.TokenType == JsonTokenType.Null) { temperature = null; } else if (reader.TokenType != JsonTokenType.Number) { throw new JsonException(); } else { temperature = reader.GetDouble(); } if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } prop = reader.GetString(); if (!string.Equals( prop, nameof(AsteroidField.MajorRadius), options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { throw new JsonException(); } if (!reader.Read() || reader.TokenType != JsonTokenType.String) { throw new JsonException(); } var majorRadius = JsonSerializer.Deserialize <HugeNumber>(ref reader, options); if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } prop = reader.GetString(); if (!string.Equals( prop, nameof(AsteroidField.MinorRadius), options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { throw new JsonException(); } if (!reader.Read() || reader.TokenType != JsonTokenType.String) { throw new JsonException(); } var minorRadius = JsonSerializer.Deserialize <HugeNumber>(ref reader, options); if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName || !reader.ValueTextEquals("Toroidal") || !reader.Read()) { throw new JsonException(); } var toroidal = reader.GetBoolean(); if (!reader.Read() || reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException(); } prop = reader.GetString(); if (!string.Equals( prop, "ChildOrbitalParameters", options.PropertyNameCaseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { throw new JsonException(); } if (!reader.Read()) { throw new JsonException(); } OrbitalParameters?childOrbitalParameters; if (reader.TokenType == JsonTokenType.Null) { childOrbitalParameters = null; } else { if (reader.TokenType != JsonTokenType.StartObject) { throw new JsonException(); } else { childOrbitalParameters = JsonSerializer.Deserialize <OrbitalParameters>(ref reader, options); } if (reader.TokenType != JsonTokenType.EndObject) { throw new JsonException(); } reader.Read(); } while (reader.TokenType != JsonTokenType.EndObject) { reader.Read(); } return(new AsteroidField( id, seed, structureType, parentId, absolutePosition, name, velocity, orbit, position, temperature, majorRadius, minorRadius, toroidal, childOrbitalParameters)); }
public override void Write(Utf8JsonWriter writer, MetastoreRegistrationResponse model, JsonSerializerOptions options) { throw new NotImplementedException(); }
/// <summary>Writes a <see cref="AsteroidField"/> as JSON.</summary> /// <param name="writer">The writer to write to.</param> /// <param name="value">The value to convert to JSON.</param> /// <param name="options">An object that specifies serialization options to use.</param> public override void Write(Utf8JsonWriter writer, AsteroidField value, JsonSerializerOptions options) { writer.WriteStartObject(); writer.WriteString( options.PropertyNamingPolicy is null ? "id" : options.PropertyNamingPolicy.ConvertName("id"), value.Id); writer.WriteString( options.PropertyNamingPolicy is null ? nameof(IIdItem.IdItemTypeName) : options.PropertyNamingPolicy.ConvertName(nameof(IIdItem.IdItemTypeName)), value.IdItemTypeName); writer.WriteNumber( options.PropertyNamingPolicy is null ? "seed" : options.PropertyNamingPolicy.ConvertName("seed"), value.Seed); writer.WriteNumber( options.PropertyNamingPolicy is null ? nameof(CosmicLocation.StructureType) : options.PropertyNamingPolicy.ConvertName(nameof(CosmicLocation.StructureType)), (int)value.StructureType); if (value.ParentId is null) { writer.WriteNull(options.PropertyNamingPolicy is null ? nameof(Location.ParentId) : options.PropertyNamingPolicy.ConvertName(nameof(Location.ParentId))); } else { writer.WriteString( options.PropertyNamingPolicy is null ? nameof(Location.ParentId) : options.PropertyNamingPolicy.ConvertName(nameof(Location.ParentId)), value.ParentId); } if (value.AbsolutePosition is null) { writer.WriteNull(options.PropertyNamingPolicy is null ? nameof(Location.AbsolutePosition) : options.PropertyNamingPolicy.ConvertName(nameof(Location.AbsolutePosition))); } else { writer.WritePropertyName(options.PropertyNamingPolicy is null ? nameof(Location.AbsolutePosition) : options.PropertyNamingPolicy.ConvertName(nameof(Location.AbsolutePosition))); JsonSerializer.Serialize(writer, value.AbsolutePosition, options); } if (value.Name is null) { writer.WriteNull(options.PropertyNamingPolicy is null ? nameof(CosmicLocation.Name) : options.PropertyNamingPolicy.ConvertName(nameof(CosmicLocation.Name))); } else { writer.WriteString( options.PropertyNamingPolicy is null ? nameof(CosmicLocation.Name) : options.PropertyNamingPolicy.ConvertName(nameof(CosmicLocation.Name)), value.Name); } writer.WritePropertyName(options.PropertyNamingPolicy is null ? nameof(CosmicLocation.Velocity) : options.PropertyNamingPolicy.ConvertName(nameof(CosmicLocation.Velocity))); JsonSerializer.Serialize(writer, value.Velocity, options); if (value.Orbit.HasValue) { writer.WritePropertyName(options.PropertyNamingPolicy is null ? nameof(CosmicLocation.Orbit) : options.PropertyNamingPolicy.ConvertName(nameof(CosmicLocation.Orbit))); JsonSerializer.Serialize(writer, value.Orbit.Value, options); } else { writer.WriteNull(options.PropertyNamingPolicy is null ? nameof(CosmicLocation.Orbit) : options.PropertyNamingPolicy.ConvertName(nameof(CosmicLocation.Orbit))); } writer.WritePropertyName(options.PropertyNamingPolicy is null ? nameof(Location.Position) : options.PropertyNamingPolicy.ConvertName(nameof(Location.Position))); JsonSerializer.Serialize(writer, value.Position, options); if (value.Material.Temperature.HasValue) { writer.WriteNumber( options.PropertyNamingPolicy is null ? nameof(IMaterial <HugeNumber> .Temperature) : options.PropertyNamingPolicy.ConvertName(nameof(IMaterial <HugeNumber> .Temperature)), value.Material.Temperature.Value); } else { writer.WriteNull(options.PropertyNamingPolicy is null ? nameof(IMaterial <HugeNumber> .Temperature) : options.PropertyNamingPolicy.ConvertName(nameof(IMaterial <HugeNumber> .Temperature))); } writer.WritePropertyName(options.PropertyNamingPolicy is null ? nameof(AsteroidField.MajorRadius) : options.PropertyNamingPolicy.ConvertName(nameof(AsteroidField.MajorRadius))); JsonSerializer.Serialize(writer, value.MajorRadius, options); writer.WritePropertyName(options.PropertyNamingPolicy is null ? nameof(AsteroidField.MinorRadius) : options.PropertyNamingPolicy.ConvertName(nameof(AsteroidField.MinorRadius))); JsonSerializer.Serialize(writer, value.MinorRadius, options); writer.WriteBoolean( options.PropertyNamingPolicy is null ? "Toroidal" : options.PropertyNamingPolicy.ConvertName("Toroidal"), value._toroidal); if (value._childOrbitalParameters.HasValue) { writer.WritePropertyName(options.PropertyNamingPolicy is null ? "ChildOrbitalParameters" : options.PropertyNamingPolicy.ConvertName("ChildOrbitalParameters")); JsonSerializer.Serialize(writer, value._childOrbitalParameters.Value, options); } else { writer.WriteNull(options.PropertyNamingPolicy is null ? "ChildOrbitalParameters" : options.PropertyNamingPolicy.ConvertName("ChildOrbitalParameters")); } writer.WriteEndObject(); }
public override void Write(Utf8JsonWriter writer, SalesforceMarketingCloudSource model, JsonSerializerOptions options) { writer.WriteObjectValue(model); }
/// <inheritdoc/> public override BigInteger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => TryGetBigInteger(ref reader, out var bi) ? bi : throw new JsonException();
static void Main(string[] args) { DateTimeOffset dateAndTime; DateTimeOffset[] dateAndTimesAvailable; // Instantiate date and time using years, months, days, // hours, minutes, and seconds dateAndTime = new DateTimeOffset(2008, 5, 1, 8, 6, 32, new TimeSpan(1, 0, 0)); DateTimeOffset dateAndTimeAvailable1 = new DateTimeOffset(2020, 2, 3, 8, 6, 32, new TimeSpan(1, 0, 0)); DateTimeOffset dateAndTimeAvailable2 = new DateTimeOffset(2020, 2, 4, 8, 6, 32, new TimeSpan(1, 0, 0)); DateTimeOffset dateAndTimeAvailable3 = new DateTimeOffset(2020, 2, 5, 8, 6, 32, new TimeSpan(1, 0, 0)); dateAndTimesAvailable = new DateTimeOffset[] { dateAndTimeAvailable1, dateAndTimeAvailable2, dateAndTimeAvailable3 }; HighLowTemps hiLo_1 = new HighLowTemps(); hiLo_1.High = 45; hiLo_1.Low = 20; HighLowTemps hiLo_2 = new HighLowTemps(); hiLo_1.High = 65; hiLo_1.Low = 30; HighLowTemps hiLo_3 = new HighLowTemps(); hiLo_1.High = 50; hiLo_1.Low = 40; var tempsHILO = new Dictionary <string, HighLowTemps>() { { "Monday", new HighLowTemps { High = 65, Low = 21 } }, { "Tuesday", new HighLowTemps { High = 35, Low = 15 } }, { "Wednesday", new HighLowTemps { High = 45, Low = 30 } } }; WeatherForecastWithPOCOs forecast1 = new WeatherForecastWithPOCOs(); forecast1.Date = dateAndTime; forecast1.TemperatureCelsius = 25; forecast1.Summary = "Weekday 3 Days"; forecast1.SummaryWords = new string[] { "Sunny", "Bright", "Warm" }; forecast1.SummaryField = "ShortRange"; forecast1.DatesAvailable = dateAndTimesAvailable; forecast1.TemperatureRanges = tempsHILO; var options = new JsonSerializerOptions { IgnoreReadOnlyProperties = false, WriteIndented = true }; string jsonString = JsonSerializer.Serialize(forecast1, options); Console.WriteLine(jsonString); string path = @"C:\_Angela\_GIT_CSharp\MiscTextFiles\WeatherReport.json"; if (File.Exists(path)) { File.Delete(path); } using (var tw = new StreamWriter(path, true)) { tw.WriteLine(jsonString.ToString()); tw.Close(); } using (var rw = new StreamReader(path)) { string fileString = rw.ReadToEnd(); rw.Close(); } /// Output looks like this: ////////////////////////////////////////////////////// // { // "Date": "2008-05-01T08:06:32+01:00", // "TemperatureCelsius": 25, // "Summary": "Weekday 3 Days", // "SummaryField": "ShortRange", // "DatesAvailable": [ // "2020-02-03T08:06:32+01:00", // "2020-02-04T08:06:32+01:00", // "2020-02-05T08:06:32+01:00" // ], // "TemperatureRanges": { // "Monday": { // "High": 65, // "Low": 21 // }, // "Tuesday": { // "High": 35, // "Low": 15 // }, // "Wednesday": { // "High": 45, // "Low": 30 // } // }, // "SummaryWords": [ // "Sunny", // "Bright", // "Warm" // ] // } ////////////////////////////////////////////////////// }
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { if (_visited.Contains(value)) { throw new JsonException("Argument is a circular structure"); } if (value == null) { writer.WriteStartObject(); writer.WriteString("v", "null"); writer.WriteEndObject(); return; } if (value is double nan && double.IsNaN(nan)) { writer.WriteStartObject(); writer.WriteString("v", "NaN"); writer.WriteEndObject(); return; } if (value is double infinity && double.IsPositiveInfinity(infinity)) { writer.WriteStartObject(); writer.WriteString("v", "Infinity"); writer.WriteEndObject(); return; } if (value is double negativeInfinity && double.IsNegativeInfinity(negativeInfinity)) { writer.WriteStartObject(); writer.WriteString("v", "-Infinity"); writer.WriteEndObject(); return; } if (value is double negativeZero && negativeZero.IsNegativeZero()) { writer.WriteStartObject(); writer.WriteString("v", "-0"); writer.WriteEndObject(); return; } if (value.GetType() == typeof(string)) { writer.WriteStartObject(); writer.WritePropertyName("s"); JsonSerializer.Serialize(writer, value); writer.WriteEndObject(); return; } if ( value.GetType() == typeof(int) || value.GetType() == typeof(decimal) || value.GetType() == typeof(long) || value.GetType() == typeof(short) || value.GetType() == typeof(double) || value.GetType() == typeof(int?) || value.GetType() == typeof(decimal?) || value.GetType() == typeof(long?) || value.GetType() == typeof(short?) || value.GetType() == typeof(double?)) { writer.WriteStartObject(); writer.WritePropertyName("n"); JsonSerializer.Serialize(writer, value); writer.WriteEndObject(); return; } if (value.GetType() == typeof(bool) || value.GetType() == typeof(bool?)) { writer.WriteStartObject(); writer.WritePropertyName("b"); JsonSerializer.Serialize(writer, value); writer.WriteEndObject(); return; } if (value is DateTime date) { writer.WriteStartObject(); writer.WritePropertyName("d"); JsonSerializer.Serialize(writer, date); writer.WriteEndObject(); return; } if (value is IDictionary dictionary && dictionary.Keys.OfType <string>().Any()) { writer.WriteStartObject(); writer.WritePropertyName("o"); writer.WriteStartArray(); _visited.Add(value); foreach (object key in dictionary.Keys) { writer.WriteStartObject(); object obj = dictionary[key]; writer.WriteString("k", key.ToString()); writer.WritePropertyName("v"); if (obj == null) { writer.WriteStartObject(); writer.WriteString("v", "null"); writer.WriteEndObject(); } else { JsonSerializer.Serialize(writer, obj, options); } writer.WriteEndObject(); } _visited.Remove(value); writer.WriteEndArray(); writer.WriteEndObject(); return; } if (value is IEnumerable array) { writer.WriteStartObject(); writer.WritePropertyName("a"); writer.WriteStartArray(); foreach (object item in array) { JsonSerializer.Serialize(writer, item, options); } writer.WriteEndArray(); writer.WriteEndObject(); return; } if (value is IChannelOwner channelOwner) { _parentObject.Handles.Add(new EvaluateArgumentGuidElement { Guid = channelOwner.Channel.Guid }); writer.WriteStartObject(); writer.WriteNumber("h", _parentObject.Handles.Count - 1); writer.WriteEndObject(); return; } writer.WriteStartObject(); writer.WritePropertyName("o"); writer.WriteStartArray(); _visited.Add(value); foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(value)) { writer.WriteStartObject(); object obj = propertyDescriptor.GetValue(value); writer.WriteString("k", propertyDescriptor.Name); writer.WritePropertyName("v"); if (obj == null) { writer.WriteStartObject(); writer.WriteString("v", "null"); writer.WriteEndObject(); } else { JsonSerializer.Serialize(writer, obj, options); } writer.WriteEndObject(); } _visited.Remove(value); writer.WriteEndArray(); writer.WriteEndObject(); }
public override ApiManagementSubscriptionUpdatedEventData Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using var document = JsonDocument.ParseValue(ref reader); return(DeserializeApiManagementSubscriptionUpdatedEventData(document.RootElement)); }
public override void Write(Utf8JsonWriter writer, AcsChatEventInThreadBaseProperties model, JsonSerializerOptions options) { writer.WriteObjectValue(model); }
/// <summary> /// Deserialize JSON into a FHIR Bundle#Response /// </summary> public static void DeserializeJsonProperty(this Bundle.ResponseComponent current, ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "status": if (reader.TokenType == JsonTokenType.Null) { current.StatusElement = new FhirString(); reader.Skip(); } else { current.StatusElement = new FhirString(reader.GetString()); } break; case "_status": if (current.StatusElement == null) { current.StatusElement = new FhirString(); } ((Hl7.Fhir.Model.Element)current.StatusElement).DeserializeJson(ref reader, options); break; case "location": if (reader.TokenType == JsonTokenType.Null) { current.LocationElement = new FhirUri(); reader.Skip(); } else { current.LocationElement = new FhirUri(reader.GetString()); } break; case "_location": if (current.LocationElement == null) { current.LocationElement = new FhirUri(); } ((Hl7.Fhir.Model.Element)current.LocationElement).DeserializeJson(ref reader, options); break; case "etag": if (reader.TokenType == JsonTokenType.Null) { current.EtagElement = new FhirString(); reader.Skip(); } else { current.EtagElement = new FhirString(reader.GetString()); } break; case "_etag": if (current.EtagElement == null) { current.EtagElement = new FhirString(); } ((Hl7.Fhir.Model.Element)current.EtagElement).DeserializeJson(ref reader, options); break; case "lastModified": if (reader.TokenType == JsonTokenType.Null) { current.LastModifiedElement = new Instant(); reader.Skip(); } else { current.LastModifiedElement = new Instant(DateTimeOffset.Parse(reader.GetString())); } break; case "_lastModified": if (current.LastModifiedElement == null) { current.LastModifiedElement = new Instant(); } ((Hl7.Fhir.Model.Element)current.LastModifiedElement).DeserializeJson(ref reader, options); break; case "outcome": current.Outcome = JsonStreamResourceConverter.PolymorphicRead(ref reader, typeof(Resource), options); break; // Complex: response, Export: ResponseComponent, Base: BackboneElement default: ((Hl7.Fhir.Model.BackboneElement)current).DeserializeJsonProperty(ref reader, options, propertyName); break; } }
/// <summary> /// Use this method to attempt to deserialize into your type based on internal buffer. Decomcrypts only apply to non-Letter data. /// <para>Combine this with AMQP header X-CR-OBJECTTYPE to get message wrapper payloads.</para> /// <para>Header Example: ("X-CR-OBJECTTYPE", "LETTER")</para> /// <para>Header Example: ("X-CR-OBJECTTYPE", "MESSAGE")</para> /// <em>Note: Always decomcrypts Letter bodies to get type regardless of parameters.</em> /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="decrypt"></param> /// <param name="decompress"></param> /// <param name="jsonSerializerOptions"></param> public async Task <TResult> GetTypeFromJsonAsync <TResult>(bool decrypt = false, bool decompress = false, JsonSerializerOptions jsonSerializerOptions = null) { switch (ContentType) { case Utils.Constants.HeaderValueForLetter: await CreateLetterFromDataAsync().ConfigureAwait(false); return(JsonSerializer.Deserialize <TResult>(Letter.Body.AsSpan(), jsonSerializerOptions)); case Utils.Constants.HeaderValueForMessage: default: if (Bytes.IsJson(Data)) { await DecomcryptDataAsync(decrypt, decompress).ConfigureAwait(false); return(JsonSerializer.Deserialize <TResult>(Data.AsSpan(), jsonSerializerOptions)); } else { return(default); } }