/// <summary> /// Parses the response received from the API /// </summary> /// <param name="response">A string of JSON data</param> public static void ParseWebResponse(string response) { if (response == "") { // TODO: Handle this } else { // Try something else if (response.Contains("<!DOCTYPE html>")) { return; } var doc = JsonDocument.Parse(response); JsonElement root = doc.RootElement; var count = 0; try { count = root.GetArrayLength(); } catch { } for (int i = 0; i < root.GetArrayLength(); i++) { string exerciseId = root[i].GetProperty("exercise_id").ToString(); string name = root[i].GetProperty("name").ToString(); string instruction = root[i].GetProperty("instruction").ToString(); string active = root[i].GetProperty("active").ToString(); string muscleGroupId = root[i].GetProperty("musclegroup").ToString(); string muscleGroupName = root[i].GetProperty("muscle_group_name").ToString(); //logger.Error($"{itemId}, {name}, {instruction}, {active}"); // Create an Exercise, and add it to the list Exercise newExercise = new Exercise(exerciseId, name, muscleGroupId, muscleGroupName, instruction, active); if (count != 1) { // Add to the dictionary to populate the dropdown lists exerciseListForDropdown.Add(exerciseId, name); exerciseList.Add(newExercise); } // We are assuming the user picked 1 exercise else if (count == 1) { singleExerciseList.Clear(); singleExerciseList.Add(newExercise); } } } }
static void _Flatten(string parentKey, JsonElement parentValue, JsonDocumentBuilder result) { switch (parentValue.ValueKind) { case JsonValueKind.Array: { if (parentValue.GetArrayLength() == 0) { result.AddProperty(parentKey, new JsonDocumentBuilder(parentValue)); } else { for (int i = 0; i < parentValue.GetArrayLength(); ++i) { var buffer = new StringBuilder(parentKey); buffer.Append('/'); buffer.Append(i.ToString()); _Flatten(buffer.ToString(), parentValue[i], result); } } break; } case JsonValueKind.Object: { if (parentValue.EnumerateObject().Count() == 0) { result.AddProperty(parentKey, new JsonDocumentBuilder(parentValue)); } else { foreach (var item in parentValue.EnumerateObject()) { var buffer = new StringBuilder(parentKey); buffer.Append('/'); buffer.Append(JsonPointer.Escape(item.Name)); _Flatten(buffer.ToString(), item.Value, result); } } break; } default: { result.AddProperty(parentKey, new JsonDocumentBuilder(parentValue)); break; } } }
public dynamic Objectify(JsonElement graphsonObject, GraphSONReader reader) { if (graphsonObject.ValueKind != JsonValueKind.Array) { return(new Dictionary <object, object>(0)); } var result = new Dictionary <object, object>(graphsonObject.GetArrayLength() / 2); for (var i = 0; i < graphsonObject.GetArrayLength(); i += 2) { result[reader.ToObject(graphsonObject[i])] = reader.ToObject(graphsonObject[i + 1]); } // IDictionary<object, object> return(result); }
private IEnumerable <IError> ParseErrors(JsonElement parent) { var length = parent.GetArrayLength(); for (var i = 0; i < length; i++) { JsonElement error = parent[i]; ErrorBuilder builder = ErrorBuilder.New(); builder.SetMessage(error.GetProperty(_message).GetString()); if (TryParseLocation(error, out IReadOnlyList <Location>?locations)) { builder.AddLocations(locations !); } if (TryParsePath(error, out IReadOnlyList <object>?path)) { builder.SetPath(path); } if (TryParseExtensions(error, out IReadOnlyDictionary <string, object?>?extensions)) { builder.SetExtensions(extensions !); } yield return(builder.Build()); } }
private static string randomListElement(JsonElement list) { int index = random.Next(list.GetArrayLength()); string word = list[index].GetString(); return(filterLegalCharacters(word)); }
protected static JsonElement?GetTokenIndex(JsonElement t, bool errorWhenNoMatch, int index) { if (t.ValueKind == JsonValueKind.Array) { if (t.GetArrayLength() <= index) { if (errorWhenNoMatch) { throw new JsonException("Index {0} outside the bounds of BsonArray.".FormatWith(CultureInfo.InvariantCulture, index)); } return(null); } return(t[index]); } else { if (errorWhenNoMatch) { throw new JsonException("Index {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, index, t.GetType().Name)); } return(null); } }
private object[] BindTypes(JsonElement jsonArray, IReadOnlyList <Type> paramTypes) { object[] arguments = null; var paramIndex = 0; var argumentsCount = jsonArray.GetArrayLength(); var paramCount = paramTypes.Count; if (argumentsCount != paramCount) { throw new InvalidDataException($"Invocation provides {argumentsCount} argument(s) but target expects {paramCount}."); } foreach (var element in jsonArray.EnumerateArray()) { if (arguments == null) { arguments = new object[paramCount]; } try { arguments[paramIndex] = BindType(element, paramTypes[paramIndex]); paramIndex++; } catch (Exception ex) { throw new InvalidDataException("Error binding arguments. Make sure that the types of the provided values match the types of the hub method being invoked.", ex); } } return(arguments ?? Array.Empty <object>()); }
/// <summary> /// <see cref="JsonElement"/>を復元する /// </summary> /// <param name="element">復元する<see cref="JsonElement"/>のインスタンス</param> /// <param name="serializer">使用するシリアライザ</param> /// <exception cref="ArgumentNullException"><paramref name="serializer"/>がnull</exception> /// <returns><paramref name="element"/>を復元したオブジェクト</returns> public object Parse(JsonElement element, BinaricJsonSerializer serializer) { if (serializer == null) { throw new ArgumentNullException(nameof(serializer), "引数がnullです"); } if (element.ValueKind == JsonValueKind.Null) { return(null); } if (element.ValueKind == JsonValueKind.Array) { var genericType = type.GetElementType(); var array = Array.CreateInstance(genericType, element.GetArrayLength()); var index = 0; var e = element.EnumerateArray(); var parser = new JsonElementParser(genericType); while (e.MoveNext()) { array.SetValue(parser.Parse(e.Current, serializer), index++); } return(array); } return(serializer.Deserialize(element.GetRawText(), type)); }
public void insertBooks(string category, int page, string clsId) { string result = HttpUtil.Get($"{baseUrl}book/list?wordFilter=0&fullFlag=0&clsIdSecond=0&pageNo={page}&orderBy=read_cnt&clsIdFirst={clsId}"); JsonElement datas = JsonSerializer.Deserialize <JsonElement>(result).GetProperty("data"); List <Hashtable> dataList = new List <Hashtable>(); for (int i = 0; i < datas.GetArrayLength(); i++) { var data = datas[i]; Hashtable ht = new Hashtable(); ht["category"] = category; ht["title"] = data.GetProperty("name").ToString(); ht["author"] = data.GetProperty("author").ToString(); ht["pic"] = data.GetProperty("photoPath").ToString(); ht["content"] = data.GetProperty("intro").ToString(); ht["tag"] = data.GetProperty("clsName").ToString(); ht["hits"] = data.GetProperty("readCnt").ToString(); ht["rating"] = data.GetProperty("strScore").ToString(); ht["rating_count"] = data.GetProperty("score").ToString(); ht["create_time"] = DateTime.Now.ToTimeStamp() / 1000; ht["reurl"] = $"{baseUrl}book/info?bookId={data.GetProperty("id").ToString()}"; dataList.Add(ht); } //var sql = DispatchProxy.Create<ISql, SqlProxy>(); //sql.Insert(); Sql sql = new Sql("novel"); sql.Insert(dataList); //sqlProxy.insert(dbDatas, "sync"); }
private global::System.Collections.Generic.IReadOnlyList <global::Demo.IVehicle> ParseGetVehiclesVehicles( JsonElement parent, string field) { JsonElement obj = parent.GetProperty(field); int objLength = obj.GetArrayLength(); var list = new global::Demo.IVehicle[objLength]; for (int objIndex = 0; objIndex < objLength; objIndex++) { JsonElement element = obj[objIndex]; string type = element.GetProperty(TypeName).GetString(); switch (type) { case "SportsCar": list[objIndex] = new SportsCar ( ); break; case "FamilyCar": list[objIndex] = new FamilyCar ( ); break; default: throw new UnknownSchemaTypeException(type); } } return(list); }
public async Task <IActionResult> GetManyById([FromBody] JsonElement items) { if (items.ValueKind == JsonValueKind.Array) { Console.WriteLine(items.GetRawText()); int length = items.GetArrayLength(); if (length == 0) { return(BadRequest()); } List <string> ids = new List <string>(length); foreach (JsonElement item in items.EnumerateArray()) { ids.Add(item.GetString()); } List <Product> list = await _context.Product.AsNoTracking() .Where(p => ids.Contains(p.Id)) .ToListAsync(); return(Ok(_mapper.Map <List <ProductReadDTO> >(list))); } return(BadRequest()); }
private global::System.Collections.Generic.IReadOnlyList <global::Elsa.OrchardCore.IWorkflowDefinitionVersion> ParseGetWorkflowDefinitionsWorkflowDefinitions( JsonElement parent, string field) { JsonElement obj = parent.GetProperty(field); int objLength = obj.GetArrayLength(); var list = new global::Elsa.OrchardCore.IWorkflowDefinitionVersion[objLength]; for (int objIndex = 0; objIndex < objLength; objIndex++) { JsonElement element = obj[objIndex]; list[objIndex] = new WorkflowDefinitionVersion ( DeserializeNullableString(element, "id"), DeserializeNullableString(element, "definitionId"), DeserializeNullableString(element, "name"), DeserializeNullableString(element, "description"), DeserializeInt(element, "version"), DeserializeBoolean(element, "isLatest"), DeserializeBoolean(element, "isPublished"), DeserializeBoolean(element, "isSingleton"), DeserializeBoolean(element, "isDisabled") ); } return(list); }
public Task VerifyListenMode(MonitorImageData imageData, SampleImageData sampleData) { return(VerifyScenarioAsync( monitorImageData: imageData, sampleImageData: sampleData, shareTmpVolume: false, listenDiagPortVolume: true, noAuthentication: true, async(monitorName, sampleName) => { if (!Config.IsHttpVerificationDisabled) { using HttpResponseMessage responseMessage = await ImageScenarioVerifier.GetHttpResponseFromContainerAsync( monitorName, DockerHelper, OutputHelper, DefaultArtifactsPort, UrlPath_Processes); JsonElement rootElement = GetContentAsJsonElement(responseMessage); // Verify returns an array with one element (the sample container process) Assert.Equal(JsonValueKind.Array, rootElement.ValueKind); Assert.Equal(1, rootElement.GetArrayLength()); } })); }
public Task VerifyMonitorNoHttpsNoAuth(MonitorImageData imageData) { return(VerifyMonitorAsync( imageData, noAuthentication: true, async containerName => { if (!Config.IsHttpVerificationDisabled) { // Verify metrics endpoint is accessible and produces zero processes using HttpResponseMessage processesMessage = await ImageScenarioVerifier.GetHttpResponseFromContainerAsync( containerName, DockerHelper, OutputHelper, DefaultArtifactsPort, UrlPath_Processes); JsonElement rootElement = GetContentAsJsonElement(processesMessage); // Verify returns an empty array (should not detect any processes) Assert.Equal(JsonValueKind.Array, rootElement.ValueKind); Assert.Equal(0, rootElement.GetArrayLength()); } }, builder => { // Reset and expose the artifacts port over http (not secure) builder.MonitorUrl(DefaultArtifactsPort); })); }
} // GetValidationClauses(...) protected override String ParseOverride(JsonElement value) { switch (value.ValueKind) { case JsonValueKind.Undefined: return("{}"); case JsonValueKind.Array: // Ensure consistency. foreach (var x in value.EnumerateArray()) { if (!x.ValueKind.DoesAgree(this.itemsKind)) { throw new FormatException("JSON type mismatch."); } } Func <JsonElement, String> parser = this.itemsKind switch { JsonSchemaValueKind.Null => (x) => "nullptr", JsonSchemaValueKind.Boolean => (x) => Boolean.Parse(x.GetRawText()).ToString().ToLowerInvariant(), JsonSchemaValueKind.Integer => (x) => Int64.Parse(x.GetRawText()).ToString(), JsonSchemaValueKind.Number => (x) => Double.Parse(x.GetRawText()).ToString(), JsonSchemaValueKind.String => (x) => x.GetRawText(), _ => throw new NotSupportedException("Primitive-typed items expected."), }; // Parse values. var items = new List <String>(value.GetArrayLength()); foreach (var x in value.EnumerateArray()) { items.Add(parser(x)); } return(String.Concat("{", String.Join(", ", items), "}")); default: throw new FormatException("JSON type mismatch."); } // switch (...) } // Parse(...)
IEnumerable <int> IArrayIndexExpression.GetIndices(JsonElement array) { var length = array.GetArrayLength(); var end = _index.IsFromEnd ? length - _index.Value : _index.Value; return(new[] { end }); }
private async Task FF_ExternalAudioOpen(string audioSource) { try { string jsonOutput = await FFProbe.GetMediaInfo(audioSource); using JsonDocument jsonDocument = JsonDocument.Parse(jsonOutput); JsonElement streamsElement = jsonDocument.RootElement.GetProperty("streams"); JsonElement audioStreamElement = new JsonElement(); // Find first audio stream for (int i = 0; i < streamsElement.GetArrayLength(); i++) { if (streamsElement[i].GetProperty("codec_type").GetString() == "audio") { audioStreamElement = streamsElement[i]; break; } } AudioTrack audioTrack = AudioTrack.FromJson(audioStreamElement); audioTracks = new AudioTrack[] { audioTrack }; ExternalAudioCodec = audioTrack.Codec; Size += audioTrack.Size; } catch (Exception) { // Since it's not possible to create a Window from this thread, every exception is rethrown; whoever called this method will have to show the user the error throw; } }
private void VisitJsonElement(JsonElement element) { switch (element.ValueKind) { case JsonValueKind.Object: foreach (JsonProperty property in element.EnumerateObject()) { VisitJsonProperty(property); } break; case JsonValueKind.Array: for (int index = 0; index < element.GetArrayLength(); index++) { EnterContext(index.ToString()); VisitJsonElement(element[index]); ExitContext(); } break; case JsonValueKind.String: case JsonValueKind.Number: case JsonValueKind.True: case JsonValueKind.False: case JsonValueKind.Null: _data.Add(new KeyValuePair <string, string>(_currentPath, element.ToString())); break; default: break; } }
private void ProcessArrayElement(JsonElement element, string elementName, TraversalArgs args) { HashSet <string> childKeys = new(); int childrenCount = element.GetArrayLength(); foreach (TraversalRule rule in args.Rules) { int childIndex = 0; childKeys.Clear(); foreach (var child in element.EnumerateArray()) { string childElementName = childIndex.ToString(); string?childKey = (rule.KeyCreator ?? _defaultArrayKeyExtractor).CreateKey(child, childElementName, elementName, childIndex, childrenCount); if (!childKeys.Add(childKey)) { // Child key was already used before. Keys should be unique. throw new LocalizationKeyIsNotUniqueException(childKey, args.IdentifierPrefix); } TraversalArgs nextArgs = args; nextArgs.Rules = rule.ChildRules; using IDisposable? loggerScope = _logger.BeginScope(childElementName); TraverseJsonElements(child, childElementName, childKey, nextArgs); childIndex++; } } }
// There are alternative solutions to this problem. // Instead of keeping track of count while enumerating the "Students" json array, use the "GetArrayLength()" method on "studentsElement". // The user may also call the Try* variations of the APIs. private static double AverageGrades_Alternative(string jsonString) { double sum = 0; int count = 0; using (JsonDocument document = JsonDocument.Parse(jsonString)) { JsonElement root = document.RootElement; JsonElement studentsElement = root.GetProperty("Students"); count = studentsElement.GetArrayLength(); foreach (JsonElement student in studentsElement.EnumerateArray()) { if (student.TryGetProperty("Grade", out JsonElement gradeElement)) { sum += gradeElement.GetDouble(); } else { sum += 70; } } } double average = sum / count; return(average); }
public void Test1(string[] args) { if (args.Length <= 0 || !File.Exists(args[0]) ) { Console.WriteLine("no data.json."); Console.ReadKey(); return; } FileStream fileStream = new FileStream(args[0], FileMode.Open, FileAccess.Read, FileShare.ReadWrite); JsonDocument jsonDocument = JsonDocument.Parse(fileStream); JsonElement jsonElement = jsonDocument.RootElement.GetProperty(nameof(BinarySearch)); int[] array1 = new int[jsonElement.GetArrayLength()]; int index = 0; foreach (var item in jsonElement.EnumerateArray()) { array1[index++] = item.GetInt32(); } Console.WriteLine(BinarySearch.IndexOf(array1, 5)); //2 Console.ReadKey(); }
private void CreateNodes() { if (_list == null) { List <JsonNode?> list; if (_jsonElement == null) { list = new List <JsonNode?>(); } else { JsonElement jElement = _jsonElement.Value; Debug.Assert(jElement.ValueKind == JsonValueKind.Array); list = new List <JsonNode?>(jElement.GetArrayLength()); foreach (JsonElement element in jElement.EnumerateArray()) { JsonNode?node = JsonNodeConverter.Create(element, Options); node?.AssignParent(this); list.Add(node); } // Clear since no longer needed. _jsonElement = null; } _list = list; } }
/// <inheritdoc/> protected override bool TryConvert(JsonElement source, out object?result) { if (source.ValueKind != JsonValueKind.Array) { result = null; return(false); } var values = new object?[source.GetArrayLength()]; var i = 0; foreach (var array in source.EnumerateArray()) { if (!_convertible.TryConvert(array, out var value)) { result = null; return(false); } values[i] = value; i++; } result = values; return(true); }
/// <summary> /// Demonstration of the JsonElement /// </summary> public static async void JsonElement_Example() { JsonDocument document = JsonDocument_ParseAsync(new JsonDocumentOptions()); JsonElement rootElement = document.RootElement; Console.WriteLine("{0}", rootElement.ValueKind); // Object // Get an individual property JsonElement element = rootElement.GetProperty("count"); Console.WriteLine("{0}", element.ValueKind); // Number Console.WriteLine("{0}", element.GetUInt32()); // 9 element = rootElement.GetProperty("next"); Console.WriteLine("{0} {1}", element.ValueKind, element.GetRawText()); // Null try { Console.WriteLine("{0}", element.GetUInt32()); // Exception } catch { Console.WriteLine("Exception as expected"); } // You can only get properties that are at the same level as the JsonElement try { element = rootElement.GetProperty("full_name"); Console.WriteLine("{0} {1}", element.ValueKind, element.GetRawText()); // Number } catch { Console.WriteLine("Exception as expected"); } JsonElement elementArray = rootElement.GetProperty("results"); Console.WriteLine("{0} {1}", elementArray.ValueKind, elementArray.GetArrayLength()); // Array // We cannot access an individual property of an object from an Array try { element = elementArray.GetProperty("full_name"); Console.WriteLine("{0} {1}", element.ValueKind, element.GetRawText()); // Number } catch { Console.WriteLine("Exception as expected"); } // Grab the first element (a JSON Object) in the array using LINQ. element = elementArray.EnumerateArray().First(); Console.WriteLine("{0}", element.ValueKind); // Object // Reference an object in the array using Item[index] element = elementArray[1]; Console.WriteLine("{0} {1}", element.ValueKind, element.GetRawText()); // Object // Access a property of the object. Console.WriteLine("{0} {1}", element.GetProperty("full_name").ValueKind, element.GetProperty("full_name").GetRawText()); // Number JsonElement.ObjectEnumerator objectEnumerator = rootElement.EnumerateObject(); foreach (JsonProperty property in objectEnumerator) { //Console.WriteLine("Element: {0}: {1}", property.Name, property.Value); } //Console.WriteLine("Item[0] {0}", rootElement); }
// More type safe than base class's ParseJson // Parse json. // [1,2,3] is a single column table, actually equivalent to: // [{Value : 1, Value: 2, Value :3 }] internal static TableValue TableFromJsonArray(JsonElement array) { Contract.Assert(array.ValueKind == JsonValueKind.Array); List <RecordValue> records = new List <RecordValue>(); for (var i = 0; i < array.GetArrayLength(); ++i) { var element = array[i]; var val = GuaranteeRecord(FormulaValue.FromJson(element)); records.Add(val); } // Constructor will handle both single-column table TableType type; if (records.Count == 0) { type = new TableType(); } else { type = TableType.FromRecord((RecordType)GuaranteeRecord(records[0]).IRContext.ResultType); } return(new InMemoryTableValue(IRContext.NotInSource(type), records.Select(r => DValue <RecordValue> .Of(r)))); }
private bool buildUnits(int section = 0) { this.textBoxes = new List <MaskedTextBox>(); int stepsLen = json.GetProperty("steps").GetArrayLength(); if (section >= stepsLen) { return(false); } JsonElement step = json.GetProperty("steps")[section]; JsonElement title = step.GetProperty("title"); JsonElement variants = step.GetProperty("variants"); int len = variants.GetArrayLength(); Title.Text = title.ToString(); Steps.Text = $"Этап {section + 1} из {stepsLen}"; for (int i = 0; i < len; i++) { MaskedTextBox tbox = buildTextBox(Container.Width, i); Label label = buildLabel(Container.Width, i, variants[i].ToString()); this.textBoxes.Add(tbox); } Button button = buildButton(); button.Location = new Point(0, Container.Controls.Find($"LabelNum{len - 1}", false).Last().Location.Y + 35); return(true); }
private VisualStudioTokenProvider[] GetTokenProviders(string tokenProviderPath) { var content = GetTokenProviderContent(tokenProviderPath); try { using JsonDocument document = JsonDocument.Parse(content); JsonElement providersElement = document.RootElement.GetProperty("TokenProviders"); var providers = new VisualStudioTokenProvider[providersElement.GetArrayLength()]; for (int i = 0; i < providers.Length; i++) { JsonElement providerElement = providersElement[i]; var path = providerElement.GetProperty("Path").GetString(); var preference = providerElement.GetProperty("Preference").GetInt32(); var arguments = GetStringArrayPropertyValue(providerElement, "Arguments"); providers[i] = new VisualStudioTokenProvider(path, arguments, preference); } Array.Sort(providers); return(providers); } catch (JsonException exception) { throw new CredentialUnavailableException($"File found at \"{tokenProviderPath}\" isn't a valid JSON file", exception); } catch (Exception exception) { throw new CredentialUnavailableException($"JSON file found at \"{tokenProviderPath}\" has invalid schema.", exception); } }
/// <summary> /// ABI decoder. Used to parse rpc responses from the EVM. /// Based on the Solidity specification <see href="https://solidity.readthedocs.io/en/v0.5.3/abi-spec.html" />. /// </summary> /// <param name="signature">Function signature i.e. <i>>(address,string,uint256)</i> or <i>>getBalance(uint256):uint256</i>. In case of the latter, the function signature will be ignored and only the return types will be parsed.</param> /// <param name="encodedData">Abi encoded values. Usually the string returned from a rpc to the EVM.</param> /// <returns>The decoded argugments for the function call given the encded data.</returns> public async Task <object[]> AbiDecode(string signature, string encodedData) { string jsonResponse = await _in3.SendRpc(In3AbiDecode, new object[] { signature, encodedData }); // This is ugly, unsemantic and error prone and SHOULD be changed. JsonElement result = (JsonElement)RpcHandler.From <object>(jsonResponse); if (result.ValueKind == JsonValueKind.String) { string singleResult = result.GetString(); return(new[] { singleResult }); } IEnumerator <JsonElement> arr = result.EnumerateArray(); object[] arrayResult = new object[result.GetArrayLength()]; int i = 0; while (arr.MoveNext()) { arrayResult[i] = arr.Current.ValueKind switch { JsonValueKind.String => arr.Current.GetString(), JsonValueKind.Number => arr.Current.GetUInt32(), JsonValueKind.False or JsonValueKind.True => arr.Current.GetBoolean(), _ => arrayResult[i] }; i++; } return(arrayResult); }
private async void DefaultMessageProcess(HttpResponseMessage message) { //TODO 还有好多要DO的……这里 HttpContent content = message.Content; string str = await content.ReadAsStringAsync(); if (string.IsNullOrWhiteSpace(str)) { return; } JsonDocument jsonDocument = JsonDocument.Parse(str); JsonElement json = jsonDocument.RootElement; try { int i = json.GetArrayLength(); for (int j = 0; j < i; ++j) { string strJson = json[0].ToString(); Request request = EntityClass.FromJson(strJson, typeof(Request)) as Request; var db = Database.Util.GetInstance(); db.Add(request); ReceiveMessage?.Invoke(request); //触发网络信息接收事件? DateTime time = request.Request_Time.AddSeconds(1); Util.AppendFile(Program.INFO_FILE, $"{time}\n"); } } catch (Exception e) { Console.WriteLine(e.Message); } }
private static void AverageGrades_Alternative(string jsonString) { // <SnippetAverageGrades2> double sum = 0; int count = 0; using (JsonDocument document = JsonDocument.Parse(jsonString)) { JsonElement root = document.RootElement; JsonElement studentsElement = root.GetProperty("Students"); count = studentsElement.GetArrayLength(); foreach (JsonElement student in studentsElement.EnumerateArray()) { if (student.TryGetProperty("Grade", out JsonElement gradeElement)) { sum += gradeElement.GetDouble(); } else { sum += 70; } } } double average = sum / count; Console.WriteLine($"Average grade : {average}"); // </SnippetAverageGrades2> }