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)); }
private bool TryParsePath(JsonElement error, out IReadOnlyList <object>?path) { if (!error.TryGetProperty(_path, out JsonElement list) || list.ValueKind == JsonValueKind.Null) { path = null; return(false); } var length = list.GetArrayLength(); var pathArray = new object[length]; for (var i = 0; i < length; i++) { JsonElement element = list[i]; if (element.ValueKind == JsonValueKind.Number) { pathArray[i] = element.GetInt32(); } else { pathArray[i] = element.GetString(); } } path = pathArray; return(true); }
private static object ParseJson(JsonElement element) { switch (element.ValueKind) { case JsonValueKind.Number: return(element.GetInt32()); case JsonValueKind.True: case JsonValueKind.False: return(element.GetBoolean()); case JsonValueKind.String: return(element.GetString()); case JsonValueKind.Array: var array = new List <object>(); foreach (var item in element.EnumerateArray()) { array.Add(ParseJson(item)); } return(array); case JsonValueKind.Object: var obj = new Dictionary <string, object>(); foreach (var prop in element.EnumerateObject()) { obj.Add(prop.Name, ParseJson(prop.Value)); } return(obj); default: return(null); } }
protected object GetValue(JsonElement elm) { object value = null; switch (elm.ValueKind) { case JsonValueKind.String: value = elm.GetString(); break; case JsonValueKind.Number: value = elm.GetInt32(); break; case JsonValueKind.True: value = elm.GetBoolean(); break; case JsonValueKind.Array: var values = new List <object>(); var enumerateArray = elm.EnumerateArray(); while (enumerateArray.MoveNext()) { values.Add(GetValue(enumerateArray.Current)); } value = values; break; } return(value); }
private static void ApplySetting(string arg, JsonElement obj, SearchSettings settings) { switch (obj.ValueKind) { case JsonValueKind.String: ApplySetting(arg, obj.GetString(), settings); break; case JsonValueKind.True: ApplySetting(arg, true, settings); break; case JsonValueKind.False: ApplySetting(arg, false, settings); break; case JsonValueKind.Number: ApplySetting(arg, obj.GetInt32().ToString(), settings); break; case JsonValueKind.Array: foreach (var arrVal in obj.EnumerateArray()) { ApplySetting(arg, arrVal, settings); } break; case JsonValueKind.Undefined: case JsonValueKind.Object: case JsonValueKind.Null: default: break; } }
public FileWrapper <T> CreateFile(T folderId, string title, JsonElement templateId, bool enableExternalExt = false) { File <T> file; if (templateId.ValueKind == JsonValueKind.Number) { file = FileStorageService.CreateNewFile(new FileModel <T, int> { ParentId = folderId, Title = title, TemplateId = templateId.GetInt32() }, enableExternalExt); } else if (templateId.ValueKind == JsonValueKind.String) { file = FileStorageService.CreateNewFile(new FileModel <T, string> { ParentId = folderId, Title = title, TemplateId = templateId.GetString() }, enableExternalExt); } else { file = FileStorageService.CreateNewFile(new FileModel <T, int> { ParentId = folderId, Title = title, TemplateId = 0 }, enableExternalExt); } return(FileWrapperHelper.Get(file)); }
private int CountChildren(JsonElement root) { // For part 2, we need to count all integers included in this object // UNLESS the object has the value "red" anywhere int ret = 0; if (root.ValueKind == JsonValueKind.Array) { foreach (var el in root.EnumerateArray()) { ret += CountChildren(el); } } else if (root.ValueKind == JsonValueKind.Object) { // Look to see if we have "red" as a value anywhere, if so, skip it foreach (var el in root.EnumerateObject()) { // For each element... if (el.Value.ValueKind == JsonValueKind.String && string.Equals("red", el.Value.GetString(), StringComparison.InvariantCultureIgnoreCase)) { return(0); } // Otherwise, add to our return ret += CountChildren(el.Value); } } else if (root.ValueKind == JsonValueKind.Number) { return(root.GetInt32()); } return(ret); }
/// <summary> /// Recursively iterates JSON element. /// </summary> /// <param name="jsonElement"></param> /// <param name="sum"></param> private void IterateJsonElement(JsonElement jsonElement, ref int sum) { switch (jsonElement.ValueKind) { case JsonValueKind.Object: if (!IsJsonObjectElementAndContainsRed(jsonElement)) { foreach (JsonProperty property in jsonElement.EnumerateObject()) { JsonElement element = property.Value; IterateJsonElement(element, ref sum); } } break; case JsonValueKind.Array: if (!IsJsonObjectElementAndContainsRed(jsonElement)) { foreach (JsonElement element in jsonElement.EnumerateArray()) { IterateJsonElement(element, ref sum); } } break; case JsonValueKind.Number: sum += jsonElement.GetInt32(); break; } }
private object GetValue(JsonElement enumValue) { switch (enumValue.ValueKind) { case JsonValueKind.String: return(enumValue.GetString()); case JsonValueKind.Number: if (enumValue.TryGetInt32(out Int32 intValue)) { return(enumValue.GetInt32()); } if (enumValue.TryGetInt64(out Int64 LongValue)) { return(enumValue.GetInt64()); } return(enumValue.GetDouble()); case JsonValueKind.True: case JsonValueKind.False: return(enumValue.GetBoolean()); case JsonValueKind.Null: return(null); default: return(enumValue.ToString()); } }
public static object GetElementValue(JsonElement element) { switch (element.ValueKind) { case JsonValueKind.Undefined: case JsonValueKind.Object: case JsonValueKind.Array: return(new JsonValue(element.GetRawText())); case JsonValueKind.String: return(element.GetString()); case JsonValueKind.Number: return(element.GetInt32()); case JsonValueKind.True: return(true); case JsonValueKind.False: return(false); case JsonValueKind.Null: return(null); default: return(element.GetRawText()); } }
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; } }
/// <summary> /// Json schema properties that contain an "anyOf" object are used as /// enumerations in glTF 2.0. /// /// This method requires that the type of the enumeration has been set. /// /// For each dictionary in the "anyOf" array, this method extracts the /// list of enumerations and appends the first element of the "enum" /// array to the Schema enum list. /// /// Additionally, when the enumeration is of type integer, the /// "description" object value is appended to the Schema enum name list. /// </summary> internal void SetValuesFromAnyOf() { if (this.Enum == null) { this.Enum = new List <object>(); } if (this.Type?[0].Name == "integer" && this.EnumNames == null) { this.EnumNames = new List <string>(); } foreach (var dict in this.AnyOf) { if (dict.Enum != null && dict.Enum.Count > 0) { JsonElement enumElement = (JsonElement)dict.Enum[0]; if (this.Type?[0].Name == "integer") { this.Enum.Add(enumElement.GetInt32()); this.EnumNames.Add(dict.Description); } else if (this.Type?[0].Name == "string") { this.Enum.Add(enumElement.GetString()); } else { throw new NotImplementedException("Enum of " + this.Type?[0].Name); } } } }
static int Sum(JsonElement elm) { return(elm.ValueKind switch { JsonValueKind.Number => elm.GetInt32(), JsonValueKind.Object => IsRed(elm) ? 0 : elm.EnumerateObject().Sum(child => Sum(child.Value)), JsonValueKind.Array => elm.EnumerateArray().Sum(child => Sum(child)), _ => 0, });
public override void SerializePrimitive <T>(ref T val) { switch (val) { case bool: Unsafe.As <T, bool>(ref val) = currentNode.GetBoolean(); break; case int: Unsafe.As <T, int>(ref val) = currentNode.GetInt32(); break; case uint: Unsafe.As <T, uint>(ref val) = currentNode.GetUInt32(); break; case float: Unsafe.As <T, float>(ref val) = currentNode.GetSingle(); break; case double: Unsafe.As <T, double>(ref val) = currentNode.GetDouble(); break; case long: Unsafe.As <T, long>(ref val) = currentNode.GetInt64(); break; case ulong: Unsafe.As <T, ulong>(ref val) = currentNode.GetUInt64(); break; case short: Unsafe.As <T, short>(ref val) = currentNode.GetInt16(); break; case ushort: Unsafe.As <T, ushort>(ref val) = currentNode.GetUInt16(); break; case char: Unsafe.As <T, char>(ref val) = (char)currentNode.GetUInt16(); break; case sbyte: Unsafe.As <T, sbyte>(ref val) = currentNode.GetSByte(); break; case byte: Unsafe.As <T, byte>(ref val) = currentNode.GetByte(); break; case decimal: Unsafe.As <T, decimal>(ref val) = currentNode.GetDecimal(); break; } }
public static void ParseUntyped() { byte[] bytes = Encoding.UTF8.GetBytes("42"); object obj = JsonSerializer.Parse(bytes, typeof(object)); Assert.IsType<JsonElement>(obj); JsonElement element = (JsonElement)obj; Assert.Equal(JsonValueType.Number, element.Type); Assert.Equal(42, element.GetInt32()); }
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 static void ParseUntyped() { object obj = JsonSerializer.Deserialize("42" u8, typeof(object)); Assert.IsType <JsonElement>(obj); JsonElement element = (JsonElement)obj; Assert.Equal(JsonValueKind.Number, element.ValueKind); Assert.Equal(42, element.GetInt32()); }
private static bool IsMatchingType(Type type, JsonElement jsonElement, JsonSerializerOptions jsonSerializerOptions, out object value) { if (IsMatchingBoolean(type, jsonElement)) { value = jsonElement.GetBoolean(); return(true); } if (IsMatchingInteger(type, jsonElement)) { value = jsonElement.GetInt32(); return(true); } if (IsMatchingDouble(type, jsonElement)) { value = jsonElement.GetDouble(); return(true); } if (IsMatchingString(type, jsonElement)) { value = jsonElement.GetString(); return(true); } if (IsMatchingObject(type, jsonElement)) { try { value = JsonSerializer.Deserialize(jsonElement.GetRawText(), type, jsonSerializerOptions); return(true); } catch (JsonException) { // Ignore if there is an error deserializing into this object type } } if (IsMatchingArray(type, jsonElement)) { try { value = JsonSerializer.Deserialize(jsonElement.GetRawText(), type, jsonSerializerOptions); return(true); } catch (JsonException) { // Ignore if there is an error deserializing into this array type } } value = null; return(false); }
public static int?ParseAsInteger(this JsonElement element, JsonParserContext context) { if (element.ValueKind == JsonValueKind.Number) { return(element.GetInt32()); } context.ReportError(EdmErrorCode.UnexpectedValueKind, Strings.CsdlJsonParser_UnexpectedJsonValueKind(element.ValueKind, context.Path, "Integer")); return(default(int?)); }
public static BaseGenerator Load(JsonElement root) { BaseGenerator generator; JsonElement typeGenerator = root.GetProperty("type"); string name = root.GetProperty("name").GetString(); JsonElement sequenceElement = root.GetProperty("sequence"); int n = root.GetProperty("count").GetInt32(); double[] sequence = new double[n]; int ndx = 0; foreach (var number in sequenceElement.EnumerateArray()) { sequence[ndx] = number.GetDouble(); ndx++; } switch ((GeneratorType)typeGenerator.GetInt32()) { case GeneratorType.BASE: generator = new BaseGenerator(name, n); break; case GeneratorType.RAND: generator = new RandomGenerator(name, n); break; case GeneratorType.STEP: double step = root.GetProperty("step").GetDouble(); generator = new GeneratorWithStep(name, n, 0, step); break; default: throw new ArgumentException("invalid json"); } for (int i = 0; i < ndx; i++) { generator.Push(sequence[i]); } JsonElement generatorsElement = root.GetProperty("generators"); foreach (var generatorElement in generatorsElement.EnumerateArray()) { BaseGenerator children = BaseGenerator.Load(generatorElement); generator.Add(children); } return(generator); }
public void EncodeStructuredModeMessage_JsonDataType_JsonElement() { var cloudEvent = new CloudEvent().PopulateRequiredAttributes(); cloudEvent.Data = ParseJson("{ \"value\": 100 }").GetProperty("value"); cloudEvent.DataContentType = "application/json"; JsonElement element = EncodeAndParseStructured(cloudEvent); JsonElement data = element.GetProperty("data"); Assert.Equal(JsonValueKind.Number, data.ValueKind); Assert.Equal(100, data.GetInt32()); }
public static int?GetIntOrNull( this JsonElement element) { try { return(element.GetInt32()); } catch (FormatException) { return(null); } }
private static int SumNumbers(JsonElement element) { // Recursively sums numbers in a Json subtree if (element.ValueKind == JsonValueKind.Number) { System.Console.WriteLine("Parse number-leaf, probably shouldn't happen"); return(element.GetInt32()); } else if (element.ValueKind == JsonValueKind.Array) { int sum = 0; foreach (JsonElement child in element.EnumerateArray()) { if (child.ValueKind == JsonValueKind.Object || child.ValueKind == JsonValueKind.Array) { sum += SumNumbers(child); } else if (child.ValueKind == JsonValueKind.Number) { sum += child.GetInt32(); } } return(sum); } else if (element.ValueKind == JsonValueKind.Object) { int sum = 0; foreach (JsonProperty property in element.EnumerateObject()) { JsonElement child = property.Value; if (child.ValueKind == JsonValueKind.String) { if (child.GetString() == "red") { return(0); // Ignore object and children } } else if (child.ValueKind == JsonValueKind.Object || child.ValueKind == JsonValueKind.Array) { // Subtree: recurse sum += SumNumbers(child); } else if (child.ValueKind == JsonValueKind.Number) { sum += child.GetInt32(); } } return(sum); } // No subtree or number found: System.Console.WriteLine("Called on a non-number leaf"); return(0); }
private static object ConvertValue(JsonElement jsonElement) { switch (jsonElement.ValueKind) { case JsonValueKind.String: return(jsonElement.GetString()); case JsonValueKind.Number: return(jsonElement.GetInt32()); } throw new NotSupportedException("Not supported json kind yet"); }
private static int SumIntegers(JsonElement element) { switch (element.ValueKind) { case JsonValueKind.Number: return(element.GetInt32()); case JsonValueKind.Array: return(element.EnumerateArray().Select(x => SumIntegers(x)).Sum()); case JsonValueKind.Object: return(element.EnumerateObject().Select(x => SumIntegers(x.Value)).Sum()); default: return(0); } }
public static void DictionaryOfObject() { Dictionary <string, object> obj = JsonSerializer.Parse <Dictionary <string, object> >(@"{""Key1"":1}"); Assert.Equal(1, obj.Count); JsonElement element = (JsonElement)obj["Key1"]; Assert.Equal(JsonValueType.Number, element.Type); Assert.Equal(1, element.GetInt32()); string json = JsonSerializer.ToString(obj); Assert.Equal(@"{""Key1"":1}", json); }
private static int?GetInt32(JsonElement element) { if (element.ValueKind == JsonValueKind.Number) { return(element.GetInt32()); } else if (element.ValueKind == JsonValueKind.String && int.TryParse(element.GetString(), out var intValue)) { return(intValue); } else { return(null); } }
private static async Task <int> GetRandomNumberAsync(HttpClient client) { if (client is null) { throw new ArgumentNullException(nameof(client)); } string json = await client.GetStringAsync("http://www.randomnumberapi.com/api/v1.0/random?min=0&max=9&count=1"); using JsonDocument document = JsonDocument.Parse(json); JsonElement root = document.RootElement; JsonElement number = root.EnumerateArray().Single(); return(number.GetInt32()); }
public async Task FlickShouldReturnLedObjectInNewState() { // Act var response = await _client.GetAsync("/api/led/3/_flick"); // Assert response.EnsureSuccessStatusCode(); JsonDocument json = await GetJsonFromContent(response); JsonElement id = json.RootElement.GetProperty("id"); JsonElement state = json.RootElement.GetProperty("state"); id.GetInt32().Should().Be(3); state.GetInt32().Should().Be(1); }
public async Task LedShouldRespondWithLedStatus() { // Act var response = await _client.GetAsync("/api/led/2"); // Assert response.EnsureSuccessStatusCode(); JsonDocument json = await GetJsonFromContent(response); JsonElement id = json.RootElement.GetProperty("id"); JsonElement state = json.RootElement.GetProperty("state"); id.GetInt32().Should().Be(2); state.GetInt32().Should().Be(0); }