Created
January 29, 2019 17:21
-
-
Save richlander/530947180fb95b4df3f1123170ba8701 to your computer and use it in GitHub Desktop.
Sample Usage of JsonDocument and JsonElement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static double ParseJson() | |
{ | |
const string json = " [ { \"name\": \"John\" }, [ \"425-000-1212\", 15 ], { \"grades\": [ 90, 80, 100, 75 ] } ]"; | |
double average = -1; | |
using (JsonDocument doc = JsonDocument.Parse(json)) | |
{ | |
JsonElement root = doc.RootElement; | |
JsonElement info = root[1]; | |
string phoneNumber = info[0].GetString(); | |
int age = info[1].GetInt32(); | |
JsonElement grades = root[2].GetProperty("grades"); | |
double sum = 0; | |
foreach (JsonElement grade in grades.EnumerateArray()) | |
{ | |
sum += grade.GetInt32(); | |
} | |
int numberOfCourses = grades.GetArrayLength(); | |
average = sum / numberOfCourses; | |
} | |
return average; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a very helpful example. Thanks.