Skip to content

Instantly share code, notes, and snippets.

@richlander
Created January 29, 2019 17:21
Show Gist options
  • Save richlander/530947180fb95b4df3f1123170ba8701 to your computer and use it in GitHub Desktop.
Save richlander/530947180fb95b4df3f1123170ba8701 to your computer and use it in GitHub Desktop.
Sample Usage of JsonDocument and JsonElement
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;
}
@macfarmw
Copy link

This is a very helpful example. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment