public static object GetValue(this JsonElement json, Type type) { switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: return(json.GetBoolean()); case TypeCode.SByte: return(json.GetSByte()); case TypeCode.Int16: return(json.GetInt16()); case TypeCode.Int32: return(json.GetInt32()); case TypeCode.Int64: return(json.GetInt64()); case TypeCode.Byte: return(json.GetByte()); case TypeCode.UInt16: return(json.GetUInt16()); case TypeCode.UInt32: return(json.GetUInt32()); case TypeCode.UInt64: return(json.GetUInt64()); case TypeCode.Single: return(json.GetSingle()); case TypeCode.Double: return(json.GetDouble()); case TypeCode.Decimal: return(json.GetDecimal()); case TypeCode.String: return(json.GetString()); case TypeCode.DateTime: return(json.GetDateTime()); } return(Convert.ChangeType(json.GetRawText(), type)); }
public static void SetValueFromJson(this PropertyInfo property, Object obj, JsonElement value, string dateTimeFormat = null) { TypeCode typeCode = Type.GetTypeCode(property.PropertyType); switch (typeCode) { case TypeCode.Int32: int int32Value = value.GetInt32(); property.SetValue(obj, int32Value); break; case TypeCode.Int64: long int64Value = value.GetInt64(); property.SetValue(obj, int64Value); break; case TypeCode.Double: double doubleValue = value.GetDouble(); property.SetValue(obj, doubleValue); break; case TypeCode.Decimal: decimal decimalValue = value.GetDecimal(); property.SetValue(obj, decimalValue); break; case TypeCode.Boolean: bool boolValue = value.GetBoolean(); property.SetValue(obj, boolValue); break; case TypeCode.DateTime: DateTime dateTimeValue; if (value.ValueKind == JsonValueKind.Null) { dateTimeValue = DateTime.MinValue; } else if (!string.IsNullOrEmpty(dateTimeFormat)) { var stringDateTimeValue = value.GetString(); dateTimeValue = DateTime.ParseExact(stringDateTimeValue, dateTimeFormat, CultureInfo.InvariantCulture); } else { dateTimeValue = value.GetDateTime(); } property.SetValue(obj, dateTimeValue); break; case TypeCode.String: string stringValue = value.GetString(); property.SetValue(obj, stringValue); break; default: //ThrowNotImplementedException(type); TODO: Сделать исключение. break; } }
public static void ExpandoObject() { ExpandoObject expando = JsonSerializer.Deserialize <ExpandoObject>(Json); Assert.Equal(8, ((IDictionary <string, object>)expando).Keys.Count); dynamic obj = expando; VerifyPrimitives(); VerifyObject(); VerifyArray(); // Re-serialize string json = JsonSerializer.Serialize <ExpandoObject>(obj); JsonTestHelper.AssertJsonEqual(Json, json); json = JsonSerializer.Serialize <dynamic>(obj); JsonTestHelper.AssertJsonEqual(Json, json); json = JsonSerializer.Serialize(obj); JsonTestHelper.AssertJsonEqual(Json, json); void VerifyPrimitives() { JsonElement jsonElement = obj.MyString; Assert.Equal("Hello", jsonElement.GetString()); jsonElement = obj.MyBoolean; Assert.True(jsonElement.GetBoolean()); jsonElement = obj.MyInt; Assert.Equal(42, jsonElement.GetInt32()); jsonElement = obj.MyDateTime; Assert.Equal(MyDateTime, jsonElement.GetDateTime()); jsonElement = obj.MyGuid; Assert.Equal(MyGuid, jsonElement.GetGuid()); } void VerifyObject() { JsonElement jsonElement = obj.MyObject; // Here we access a property on a nested object and must use JsonElement (not a dynamic property). Assert.Equal("World", jsonElement.GetProperty("MyString").GetString()); } void VerifyArray() { JsonElement jsonElement = obj.MyArray; Assert.Equal(2, jsonElement.EnumerateArray().Count()); } }
public override object?Invert(JsonElement value) { if (value.ValueKind == JsonValueKind.Null) { return(null); } return(columnType switch { DValueType.Bool => value.GetBoolean(), DValueType.Integer => value.GetInt64(), DValueType.Real => value.GetDouble(), DValueType.Date => value.GetDateTime(), DValueType.Datetime => value.GetDateTime(), DValueType.Text => value.GetString(), DValueType.Timestamp => value.GetDateTime(), DValueType.Unknown => value.GetString(), _ => throw new InvalidOperationException($"Unknown column type <{columnType}>"), });
public static DateTime AsDateTime(JsonElement element) { switch (element.ValueKind) { case JsonValueKind.String: return(element.GetDateTime()); default: throw new NotSupportedException(); } }
public static object ToObject(this JsonElement element, ColumnType columnType) { return(columnType switch { ColumnType.Boolean => element.GetBoolean(), ColumnType.Decimal => element.GetDecimal(), ColumnType.Integer => element.GetInt64(), ColumnType.String => element.GetString(), ColumnType.DateTime => element.GetDateTime(), _ => throw new ArgumentException($"Unsupported columnType conversion [{columnType}]", nameof(columnType)) });
private object BindType(JsonElement jsonObject, Type type) { if (type == typeof(DateTime)) { return(jsonObject.GetDateTime()); } else if (type == typeof(DateTimeOffset)) { return(jsonObject.GetDateTimeOffset()); } return(JsonSerializer.Parse(jsonObject.GetRawText(), type, _payloadSerializerOptions)); }
public static object Cast(this JsonElement fromValue, Field field) { switch (field.DataType) { case DataTypeEnum.Booelan: return(fromValue.GetBoolean()); case DataTypeEnum.Integer: case DataTypeEnum.Float: return(fromValue.GetDouble()); case DataTypeEnum.String: case DataTypeEnum.GUID: return(fromValue.GetString()); case DataTypeEnum.DateTime: case DataTypeEnum.Date: return(fromValue.GetDateTime()); case DataTypeEnum.Time: var val = fromValue.GetDateTime(); return(new TimeSpan(val.Hour, val.Minute, val.Second)); case DataTypeEnum.Binary: return(fromValue.GetBytesFromBase64()); case DataTypeEnum.Void: case DataTypeEnum.Array: throw new NotImplementedException(); case DataTypeEnum.Object: throw new NotImplementedException(); default: throw new NotImplementedException(); } }
private object BindType(JsonElement jsonObject, Type type) { if (type == typeof(DateTime)) { return(jsonObject.GetDateTime()); } else if (type == typeof(DateTimeOffset)) { return(jsonObject.GetDateTimeOffset()); } if (jsonObject.Type == JsonValueType.Null) { return(null); } return(JsonSerializer.Parse(jsonObject.GetRawText(), type)); }
public static object ConsumeJsonElement(Type targetReturnType, JsonElement e) { // ReSharper disable once HeapView.BoxingAllocation object ParseNumber(JsonElement el) { if (el.TryGetInt64(out var l)) { return(l); } return(el.GetDouble()); } return(targetReturnType switch { _ when targetReturnType == typeof(bool) => e.GetBoolean(), _ when targetReturnType == typeof(byte) => e.GetByte(), _ when targetReturnType == typeof(decimal) => e.GetDecimal(), _ when targetReturnType == typeof(double) => e.GetDouble(), _ when targetReturnType == typeof(Guid) => e.GetGuid(), _ when targetReturnType == typeof(short) => e.GetInt16(), _ when targetReturnType == typeof(int) => e.GetInt32(), _ when targetReturnType == typeof(long) => e.GetInt64(), _ when targetReturnType == typeof(float) => e.GetSingle(), _ when targetReturnType == typeof(string) => e.GetString(), _ when targetReturnType == typeof(DateTime) => e.GetDateTime(), _ when targetReturnType == typeof(DateTimeOffset) => e.GetDateTimeOffset(), _ when targetReturnType == typeof(ushort) => e.GetUInt16(), _ when targetReturnType == typeof(uint) => e.GetUInt32(), _ when targetReturnType == typeof(ulong) => e.GetUInt64(), _ when targetReturnType == typeof(sbyte) => e.GetSByte(), _ when targetReturnType == typeof(DynamicDictionary) => DynamicDictionary.Create(e), _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.Array => e.EnumerateArray().Select(je => ConsumeJsonElement(targetReturnType, je)).ToArray(), _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.Object => e.ToDictionary(), _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.True => true, _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.False => false, _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.Null => null, _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.String => e.GetString(), _ when targetReturnType == typeof(object) && e.ValueKind == JsonValueKind.Number => ParseNumber(e), _ => null });
public override object?Invert(JsonElement value) { if (value.ValueKind == JsonValueKind.Null) { return(null); } var lowerBound = value.GetDateTime(); return(dateInterval switch { // Add a random offset at the next lower level of granularity. "year" => lowerBound.AddMonths(rng.Next(12)), "quarter" => lowerBound.AddMonths(rng.Next(3)), "month" => lowerBound.AddDays(rng.NextDouble() * DateTime.DaysInMonth(lowerBound.Year, lowerBound.Month)), "day" => lowerBound.AddHours(rng.NextDouble() * 24), "hour" => lowerBound.AddMinutes(rng.NextDouble() * 60), "minute" => lowerBound.AddSeconds(rng.NextDouble() * 60), "second" => lowerBound.AddMilliseconds(rng.NextDouble() * 1000), _ => lowerBound, });
private void ProcessJournalFileUpdate(string journalFile) { long filePointer = 0; if (_filePointers.ContainsKey(journalFile)) { filePointer = _filePointers[journalFile]; } string newJournalEvents = ""; try { // Read the file - we open in file share mode as E: D will be constantly writing to this file if (_journalFileStream == null) { _journalFileStream = new FileStream(journalFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); } if (filePointer > _journalFileStream.Length) { filePointer = 0; } _journalFileStream.Seek(filePointer, SeekOrigin.Begin); filePointer = _journalFileStream.Length; using (StreamReader sr = new StreamReader(_journalFileStream, Encoding.Default, true, 1000, true)) newJournalEvents = sr.ReadToEnd(); if (!_journalFileStream.CanSeek) { // We only close the file if we can't seek (no point in continuously reopening) _journalFileStream.Close(); _journalFileStream = null; } else { if (_filePointers.ContainsKey(journalFile)) { _filePointers[journalFile] = filePointer; } else { _filePointers.Add(journalFile, filePointer); } } } catch { } if (String.IsNullOrEmpty(newJournalEvents)) { return; } string[] journalEvents = newJournalEvents.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (string journalEvent in journalEvents) { try { using (JsonDocument jsonDoc = JsonDocument.Parse(journalEvent)) { JsonElement timestampElement = jsonDoc.RootElement.GetProperty("timestamp"); if (DateTime.UtcNow.Subtract(timestampElement.GetDateTime()).TotalSeconds < 10) { JsonElement eventElement = jsonDoc.RootElement.GetProperty("event"); string eventName = eventElement.GetString(); if (eventName.Equals("Shutdown")) { // We won't receive any more events into this log file // Chances are we're shutting down, but we'll go into slow ping mode in case it is a game restart _statusCheckTimer.Interval = 10000; _activeJournalFile = ""; _journalFileStream?.Close(); _journalFileStream = null; } else if (eventName.Equals("Continued")) { // We won't receive any more events into this log file, but a new one should be created _activeJournalFile = ""; _journalFileStream?.Close(); _journalFileStream = null; } else if (eventName.Equals("Commander")) { // This event gives us the Commander name JsonElement commanderNameElement = jsonDoc.RootElement.GetProperty("Name"); CommanderName = commanderNameElement.GetString(); } else if (ReportEvents.Contains(eventName)) { // This is an event we are interested in //File.AppendAllText("journalevents.log", $"{journalEvent}{Environment.NewLine}"); InterestingEventOccurred?.Invoke(this, journalEvent.Trim()); } } } } catch { } } }
public static object ToObject(this JsonElement element, Type type) { object result = null; var nonNullType = Nullable.GetUnderlyingType(type); if (nonNullType != null) { type = nonNullType; } switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: result = element.GetBoolean(); break; case TypeCode.Byte: result = element.GetByte(); break; case TypeCode.SByte: result = element.GetSByte(); break; case TypeCode.Int16: result = element.GetInt16(); break; case TypeCode.UInt16: result = element.GetUInt16(); break; case TypeCode.Int32: result = element.GetInt32(); break; case TypeCode.UInt32: result = element.GetUInt32(); break; case TypeCode.Int64: result = element.GetInt64(); break; case TypeCode.UInt64: result = element.GetUInt64(); break; case TypeCode.Single: result = element.GetSingle(); break; case TypeCode.Double: result = element.GetDouble(); break; case TypeCode.Decimal: result = element.GetDecimal(); break; case TypeCode.DateTime: result = element.GetDateTime(); break; case TypeCode.String: result = element.GetString(); break; default: if (type == typeof(Guid)) { result = element.GetGuid(); break; } throw new NotImplementedException(); } if (nonNullType != null) { return(result.ToNullable()); } return(result); }
private static object DeserializeJsonValue(Type type, JsonElement value) { if (value.ValueKind == JsonValueKind.Null && (type == typeof(string) || Nullable.GetUnderlyingType(type) != null)) { return(null); } else if (type == typeof(bool) || type == typeof(bool?)) { return(value.GetBoolean()); } else if (type == typeof(byte) || type == typeof(byte?)) { return(value.GetByte()); } else if (type == typeof(short) || type == typeof(short?)) { return(value.GetInt16()); } else if (type == typeof(ushort) || type == typeof(ushort?)) { return(value.GetUInt16()); } else if (type == typeof(int) || type == typeof(int?)) { return(value.GetInt32()); } else if (type == typeof(uint) || type == typeof(uint?)) { return(value.GetUInt32()); } else if (type == typeof(long) || type == typeof(long?)) { return(value.GetInt64()); } else if (type == typeof(ulong) || type == typeof(ulong?)) { return(value.GetUInt64()); } else if (type == typeof(float) || type == typeof(float?)) { return(value.GetSingle()); } else if (type == typeof(double) || type == typeof(double?)) { return(value.GetDouble()); } else if (type == typeof(decimal) || type == typeof(decimal?)) { return(value.GetDecimal()); } else if (type == typeof(DateTime) || type == typeof(DateTime?)) { return(value.GetDateTime()); } else if (type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?)) { return(value.GetDateTimeOffset()); } else if (type == typeof(TimeSpan) || type == typeof(TimeSpan?)) { return(TimeSpan.Parse(value.GetString())); } else if (type == typeof(string)) { return(value.GetString()); } else { return(JsonSerializer.Deserialize(value.GetRawText(), type)); } }
protected void AssertJsonValue(JsonElement expected, object actual) { bool switched = true; switch (actual) { case Guid guid: Assert.Equal(new Guid(expected.GetString()), guid); break; case DateTime dateTime: Assert.Equal(expected.GetDateTime(), dateTime); break; case DateTimeOffset dateTime: Assert.Equal(expected.GetDateTimeOffset(), dateTime); break; case TimeSpan timeSpan: Assert.Equal(TimeSpan.FromSeconds(expected.GetInt32()), timeSpan); break; case int @int: if (expected.ValueKind == JsonValueKind.String) { Assert.Equal(int.Parse(expected.GetString()), @int); } else { Assert.Equal(expected.GetInt32(), @int); } break; case long @long: if (expected.ValueKind == JsonValueKind.String) { Assert.Equal(long.Parse(expected.GetString()), @long); } else { Assert.Equal(expected.GetInt64(), @long); } break; case double @double: Assert.Equal(expected.GetDouble(), @double, 10); break; case bool @bool: Assert.Equal(expected.GetBoolean(), @bool); break; case string @string: Assert.Equal(expected.GetString(), @string); break; case null: if (expected.ValueKind == JsonValueKind.String) { Assert.Equal(expected.GetString(), string.Empty); } break; default: switched = false; break; } if (!switched) { var type = actual !.GetType(); if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ApiEnum <>)) { var enumType = type.GenericTypeArguments[0]; dynamic @enum = actual; // Just for easiness Assert.Equal(expected.GetString(), @enum.RawValue); if (@enum.IsUnknown) { var enumNames = Enum.GetNames(enumType) .Select(x => enumType.GetField(x).GetCustomAttribute <EnumMemberAttribute>()?.Value ?? x); Assert.True(enumNames.Contains((string)@enum.RawValue, StringComparer.OrdinalIgnoreCase), $"Expected '{expected}' to be a value in enumerator {@enum.Value.GetType().FullName}; detected value '{@enum.Value}'"); } dynamic expectedEnum = Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, new[] { expected.GetString() }, null); Assert.Equal(expectedEnum.Value, @enum.Value); switched = true; } } if (!switched) { Assert.Equal(expected.GetString(), actual !.ToString()); } }
private static object WithValue(this PropertyInfo property, JsonElement value) { var propType = property.PropertyType; if (value.ValueKind == JsonValueKind.Null) { return(propType.GetDefaultValue()); } else if (typeof(bool) == propType) { return(value.GetBoolean()); } else if (typeof(int) == propType) { return(value.GetInt32()); } else if (typeof(uint) == propType) { return(value.GetUInt32()); } else if (typeof(short) == propType) { return(value.GetInt16()); } else if (typeof(ushort) == propType) { return(value.GetUInt16()); } else if (typeof(long) == propType) { return(value.GetInt64()); } else if (typeof(ulong) == propType) { return(value.GetUInt64()); } else if (typeof(string) == propType) { return(value.GetString()); } else if (typeof(byte) == propType) { return(value.GetByte()); } else if (typeof(sbyte) == propType) { return(value.GetSByte()); } else if (typeof(DateTime) == propType) { return(value.GetDateTime()); } else if (typeof(DateTimeOffset) == propType) { return(value.GetDateTimeOffset()); } else if (typeof(double) == propType) { return(value.GetDouble()); } else if (typeof(float) == propType) { return(value.GetSingle()); } else if (typeof(Guid) == propType) { return(value.GetGuid()); } else if (typeof(decimal) == propType) { return(value.GetDecimal()); } else if (value.GetType() == propType) { return(value); } else { return(value.ToObject(propType)); } }
private static object ParseValue(JsonElement jsonEl, Type type) { var valueKind = jsonEl.ValueKind; var targetType = type; var isNullable = false; var nullableType = Nullable.GetUnderlyingType(type); if (nullableType != null) { targetType = nullableType; isNullable = true; } if (targetType.IsEnum) { targetType = Enum.GetUnderlyingType(targetType); } switch (valueKind) { case JsonValueKind.Array: case JsonValueKind.Null: case JsonValueKind.Undefined: case JsonValueKind.Object: return(isNullable ? null : targetType.GetDefault()); case JsonValueKind.False: case JsonValueKind.True: return(jsonEl.GetBoolean()); case JsonValueKind.String: return(targetType == typeof(string) ? jsonEl.GetString() : targetType == typeof(DateTime) ? jsonEl.GetDateTime() : targetType == typeof(Guid) ? jsonEl.GetGuid() : targetType.GetDefault()); case JsonValueKind.Number: return(targetType == typeof(byte) ? jsonEl.GetByte() : targetType == typeof(decimal) ? jsonEl.GetDecimal() : targetType == typeof(double) ? jsonEl.GetDouble() : targetType == typeof(short) ? jsonEl.GetInt16() : targetType == typeof(int) ? jsonEl.GetInt32() : targetType == typeof(long) ? jsonEl.GetInt64() : targetType == typeof(sbyte) ? jsonEl.GetSByte() : targetType == typeof(float) ? jsonEl.GetSingle() : targetType == typeof(ushort) ? jsonEl.GetUInt16() : targetType == typeof(uint) ? jsonEl.GetUInt32() : targetType == typeof(ulong) ? jsonEl.GetUInt64() : targetType.GetDefault()); default: return(targetType.GetDefault()); } }
public static object GetValue(JsonElement jsonElement) { if (_columnDataType == typeof(DateTime)) { return(jsonElement.GetDateTime()); } else if (_columnDataType.IsEnum) { if (jsonElement.ValueKind == JsonValueKind.Number) { return(Enum.Parse(THelper.GetUnderlyingType <TValue>(), jsonElement.GetInt32().ToString())); } else { return(Enum.Parse(THelper.GetUnderlyingType <TValue>(), jsonElement.GetString())); } } else if (_columnDataType == typeof(byte)) { return(jsonElement.GetByte()); } else if (_columnDataType == typeof(decimal)) { return(jsonElement.GetDecimal()); } else if (_columnDataType == typeof(double)) { return(jsonElement.GetDouble()); } else if (_columnDataType == typeof(short)) { return(jsonElement.GetInt16()); } else if (_columnDataType == typeof(int)) { return(jsonElement.GetInt32()); } else if (_columnDataType == typeof(long)) { return(jsonElement.GetInt64()); } else if (_columnDataType == typeof(sbyte)) { return(jsonElement.GetSByte()); } else if (_columnDataType == typeof(float)) { return(jsonElement.GetSingle()); } else if (_columnDataType == typeof(ushort)) { return(jsonElement.GetUInt16()); } else if (_columnDataType == typeof(uint)) { return(jsonElement.GetUInt32()); } else if (_columnDataType == typeof(ulong)) { return(jsonElement.GetUInt64()); } else if (_columnDataType == typeof(Guid)) { return(jsonElement.GetGuid()); } else if (_columnDataType == typeof(bool)) { if (jsonElement.ValueKind == JsonValueKind.True) { return(true); } else { return(false); } } else { return(jsonElement.GetString()); } }