You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Refactor, improve the WebAPIClient tutorial page to use GetFromJsonAsync instead of DeserializeAsync (#48202)
* Use Net.Http.Json extension method GetFromJsonAsync instead of JsonSerializer
* Remove configuring the deserialization
* Capitalize the Name property
* Update Repository class
* Remove unused Text.Json.Serialization
* Correct the orders of points
* WriteLine instead of Write in early phase to improve output readability
* Revert "Correct the orders of points"
This reverts commit bb708ac.
* Remove leftover sentence
* Mention that GetFromJsonAsync is case-insensitive
This is mentioned in two places - with the C# naming convention, where
it's worth to mention why we keep on having uppercase, and in the Repository
class defining, where we would normally had to make a conversion, but
now we don't because we have case-insensitive method as a tool.
Copy file name to clipboardExpand all lines: docs/csharp/tutorials/console-webapiclient.md
+22-54Lines changed: 22 additions & 54 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -121,35 +121,31 @@ Use the <xref:System.Net.Http.HttpClient> class to make HTTP requests. <xref:Sys
121
121
122
122
## Deserialize the JSON Result
123
123
124
-
The following steps convert the JSON response into C# objects. You use the <xref:System.Text.Json.JsonSerializer?displayProperty=nameWithType> class to deserialize JSON into objects.
124
+
The following steps simplify the approach to fetching the data and processing it. You will use the <xref:System.Net.Http.Json.HttpClientJsonExtensions.GetFromJsonAsync%2A> extension method that's part of the [📦 System.Net.Http.Json](https://www.nuget.org/packages/System.Net.Http.Json) NuGet package to fetch and deserialize the JSON results into objects.
125
125
126
126
1. Create a file named *Repository.cs* and add the following code:
127
127
128
128
```csharp
129
-
publicrecordclassRepository(stringname);
129
+
publicrecordclassRepository(stringName);
130
130
```
131
131
132
132
The preceding code defines a class to represent the JSON object returned from the GitHub API. You'll use this class to display a list of repository names.
133
133
134
-
The JSON for a repository object contains dozens of properties, but only the `name` property will be deserialized. The serializer automatically ignores JSON properties for which there is no match in the target class. This feature makes it easier to create types that work with only a subset of fields in a large JSON packet.
134
+
The JSON for a repository object contains dozens of properties, but only the `Name` property will be deserialized. The serializer automatically ignores JSON properties for which there is no match in the target class. This feature makes it easier to create types that work with only a subset of fields in a large JSON packet.
135
135
136
-
The C# convention is to [capitalize the first letter of property names](../../standard/design-guidelines/capitalization-conventions.md), but the `name` property here starts with a lowercase letter because that matches exactly what's in the JSON. Later you'll see how to use C# property names that don't match the JSON property names.
136
+
Although the `GetFromJsonAsync` method you will use in the next point has a benefit of being case-insensitive when it comes to property names, the C# convention is to [capitalize the first letter of property names](../../standard/design-guidelines/capitalization-conventions.md).
137
137
138
-
1. Use the serializer to convert JSON into C# objects. Replace the call to
139
-
<xref:System.Net.Http.HttpClient.GetStringAsync(System.String)> in the `ProcessRepositoriesAsync` method with the following lines:
138
+
1. Use the <xref:System.Net.Http.Json.HttpClientJsonExtensions.GetFromJsonAsync%2A?displayProperty=nameWithType> method to fetch and convert JSON into C# objects. Replace the call to <xref:System.Net.Http.HttpClient.GetStringAsync(System.String)> in the `ProcessRepositoriesAsync` method with the following lines:
The updated code replaces <xref:System.Net.Http.HttpClient.GetStringAsync(System.String)> with <xref:System.Net.Http.HttpClient.GetStreamAsync(System.String)>. This serializer method uses a stream instead of a string as its source.
The first argument to <xref:System.Text.Json.JsonSerializer.DeserializeAsync%60%601(System.IO.Stream,System.Text.Json.JsonSerializerOptions,System.Threading.CancellationToken)?displayProperty=nameWithType>is an `await` expression. `await` expressions can appear almost anywhere in your code, even though up to now, you've only seen them as part of an assignment statement. The other two parameters, `JsonSerializerOptions`and `CancellationToken`, are optional and are omitted in the code snippet.
146
+
Thefirstargumentto`GetFromJsonAsync` methodisan `await` expression. `await` expressionscanappearalmostanywhereinyourcode, eventhoughuptonow, you've only seen them as part of an assignment statement. The next parameter, `requestUri` is optional and doesn'thavetobeprovidedifwasalreadyspecifiedwhencreatingthe `client` object. Youdidn't provide the `client` object with the URI to send request to, so you specified the URI now. The last optional parameter, the `CancellationToken` is omitted in the code snippet.
151
147
152
-
The `DeserializeAsync` method is [*generic*](../fundamentals/types/generics.md), which means you supply type arguments for what kind of objects should be created from the JSON text. In this example, you're deserializing to a `List<Repository>`, which is another generic object, a <xref:System.Collections.Generic.List%601?displayProperty=nameWithType>. The `List<T>` class stores a collection of objects. The type argument declares the type of objects stored in the `List<T>`. The type argument is your `Repository` record, because the JSON text represents a collection of repository objects.
148
+
The `GetFromJsonAsync` methodis [*generic*](../fundamentals/types/generics.md), whichmeansyousupplytypeargumentsfor what kind of objects should be created from the fetched JSON text. In this example, you're deserializing to a `List<Repository>`, which is another generic object, a <xref:System.Collections.Generic.List%601?displayProperty=nameWithType>. The `List<T>` class stores a collection of objects. The type argument declares the type of objects stored in the `List<T>`. The type argument is your `Repository` record, because the JSON text represents a collection of repository objects.
153
149
154
150
1. Add code to display the name of each repository. Replace the lines that read:
155
151
@@ -161,14 +157,14 @@ The following steps convert the JSON response into C# objects. You use the <xref
The `ProcessRepositoriesAsync` method can do the async work and return a collection of the repositories. Change that method to return `Task<List<Repository>>`, and move the code that writes to the console near its caller.
@@ -219,10 +188,7 @@ The `ProcessRepositoriesAsync` method can do the async work and return a collect
219
188
1. Return the repositories after processing the JSON response:
JSONmostoftenuseslowercasefor names of it's objects, however we don't need to make any conversion and can keep the uppercase of the fields names, because, like mentioned in one of previous points, the `GetFromJsonAsync` extension method is case-insensitive when it comes to property names.
230
+
263
231
1. Update the `foreach` loop in the *Program.cs* file to display the property values:
0 commit comments