Skip to content

Commit 03fbaad

Browse files
Updating JSON Package Readme (#90102)
* Updating Json package readme * Update src/libraries/System.Text.Json/src/PACKAGE.md Co-authored-by: Eirik Tsarpalis <[email protected]> * Apply suggestions from code review Co-authored-by: Eirik Tsarpalis <[email protected]> * Remove sharplab comment * Update PACKAGE.md * Update PACKAGE.md * Remove TODO --------- Co-authored-by: Eirik Tsarpalis <[email protected]>
1 parent e52ddd4 commit 03fbaad

File tree

1 file changed

+251
-5
lines changed

1 file changed

+251
-5
lines changed
Lines changed: 251 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,257 @@
11
## About
22

3+
<!-- A description of the package and where one can find more documentation -->
4+
35
Provides high-performance and low-allocating types that serialize objects to JavaScript Object Notation (JSON) text and deserialize JSON text to objects, with UTF-8 support built-in. Also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM), that is read-only, for random access of the JSON elements within a structured view of the data.
46

5-
The `System.Text.Json` library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.
7+
## Key Features
8+
9+
<!-- The key features of this package -->
10+
11+
* High-performance reader and writer types for UTF-8 encoded JSON.
12+
* A fully-featured JSON serializer for .NET types using reflection or source generated contracts.
13+
* A high-performance read-only JSON DOM (JsonDocument) and a mutable DOM that interoperates with the serializer (JsonNode).
14+
* Built-in support for async serialization, including IAsyncEnumerable support.
15+
* Fully customizable contract model for serializable types.
16+
17+
## How to Use
18+
19+
<!-- A compelling example on how to use this package with code, as well as any specific guidelines for when to use the package -->
20+
21+
The System.Text.Json library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use the most recent version in older target frameworks.
22+
23+
Serialization:
24+
```csharp
25+
using System;
26+
using System.Text.Json;
27+
28+
WeatherForecast forecast = new (DateTimeOffset.Now, 26.6f, "Sunny");
29+
var serialized = JsonSerializer.Serialize(forecast);
30+
31+
Console.WriteLine(serialized);
32+
// {"Date":"2023-08-02T16:01:20.9025406+00:00","TemperatureCelsius":26.6,"Summary":"Sunny"}
33+
34+
var forecastDeserialized = JsonSerializer.Deserialize<WeatherForecast>(serialized);
35+
Console.WriteLine(forecast == forecastDeserialized);
36+
// True
37+
38+
public record WeatherForecast(DateTimeOffset Date, float TemperatureCelsius, string? Summary);
39+
```
40+
41+
Serialization using the source generator:
42+
```csharp
43+
using System.Text.Json;
44+
using System.Text.Json.Serialization;
45+
46+
WeatherForecast forecast = new (DateTimeOffset.Now, 26.6f, "Sunny");
47+
var serialized = JsonSerializer.Serialize(forecast, SourceGenerationContext.Default.WeatherForecast);
48+
49+
Console.WriteLine(serialized);
50+
// {"Date":"2023-08-02T16:01:20.9025406+00:00","TemperatureCelsius":26.6,"Summary":"Sunny"}
51+
52+
var forecastDeserialized = JsonSerializer.Deserialize<WeatherForecast>(serialized, SourceGenerationContext.Default.WeatherForecast);
53+
Console.WriteLine(forecast == forecastDeserialized);
54+
// True
55+
56+
public record WeatherForecast(DateTimeOffset Date, float TemperatureCelsius, string? Summary);
57+
58+
[JsonSourceGenerationOptions(WriteIndented = true)]
59+
[JsonSerializable(typeof(WeatherForecast))]
60+
internal partial class SourceGenerationContext : JsonSerializerContext
61+
{
62+
}
63+
```
64+
65+
Using the JSON DOM:
66+
```csharp
67+
68+
using System;
69+
using System.Text.Json;
70+
using System.Text.Json.Nodes;
71+
72+
string jsonString =
73+
@"{
74+
""Date"": ""2019-08-01T00:00:00"",
75+
""Temperature"": 25,
76+
""Summary"": ""Hot"",
77+
""DatesAvailable"": [
78+
""2019-08-01T00:00:00"",
79+
""2019-08-02T00:00:00""
80+
],
81+
""TemperatureRanges"": {
82+
""Cold"": {
83+
""High"": 20,
84+
""Low"": -10
85+
},
86+
""Hot"": {
87+
""High"": 60,
88+
""Low"": 20
89+
}
90+
}
91+
}
92+
";
93+
94+
JsonNode forecastNode = JsonNode.Parse(jsonString)!;
95+
96+
97+
// Get value from a JsonNode.
98+
JsonNode temperatureNode = forecastNode["Temperature"]!;
99+
Console.WriteLine($"Type={temperatureNode.GetType()}");
100+
Console.WriteLine($"JSON={temperatureNode.ToJsonString()}");
101+
//output:
102+
//Type = System.Text.Json.Nodes.JsonValue`1[System.Text.Json.JsonElement]
103+
//JSON = 25
104+
105+
// Get a typed value from a JsonNode.
106+
int temperatureInt = (int)forecastNode["Temperature"]!;
107+
Console.WriteLine($"Value={temperatureInt}");
108+
//output:
109+
//Value=25
110+
111+
// Get a typed value from a JsonNode by using GetValue<T>.
112+
temperatureInt = forecastNode["Temperature"]!.GetValue<int>();
113+
Console.WriteLine($"TemperatureInt={temperatureInt}");
114+
//output:
115+
//Value=25
116+
117+
// Get a JSON object from a JsonNode.
118+
JsonNode temperatureRanges = forecastNode["TemperatureRanges"]!;
119+
Console.WriteLine($"Type={temperatureRanges.GetType()}");
120+
Console.WriteLine($"JSON={temperatureRanges.ToJsonString()}");
121+
//output:
122+
//Type = System.Text.Json.Nodes.JsonObject
123+
//JSON = { "Cold":{ "High":20,"Low":-10},"Hot":{ "High":60,"Low":20} }
124+
125+
// Get a JSON array from a JsonNode.
126+
JsonNode datesAvailable = forecastNode["DatesAvailable"]!;
127+
Console.WriteLine($"Type={datesAvailable.GetType()}");
128+
Console.WriteLine($"JSON={datesAvailable.ToJsonString()}");
129+
//output:
130+
//datesAvailable Type = System.Text.Json.Nodes.JsonArray
131+
//datesAvailable JSON =["2019-08-01T00:00:00", "2019-08-02T00:00:00"]
132+
133+
// Get an array element value from a JsonArray.
134+
JsonNode firstDateAvailable = datesAvailable[0]!;
135+
Console.WriteLine($"Type={firstDateAvailable.GetType()}");
136+
Console.WriteLine($"JSON={firstDateAvailable.ToJsonString()}");
137+
//output:
138+
//Type = System.Text.Json.Nodes.JsonValue`1[System.Text.Json.JsonElement]
139+
//JSON = "2019-08-01T00:00:00"
140+
141+
// Get a typed value by chaining references.
142+
int coldHighTemperature = (int)forecastNode["TemperatureRanges"]!["Cold"]!["High"]!;
143+
Console.WriteLine($"TemperatureRanges.Cold.High={coldHighTemperature}");
144+
//output:
145+
//TemperatureRanges.Cold.High = 20
146+
147+
// Parse a JSON array
148+
JsonNode datesNode = JsonNode.Parse(@"[""2019-08-01T00:00:00"",""2019-08-02T00:00:00""]")!;
149+
JsonNode firstDate = datesNode[0]!.GetValue<DateTime>();
150+
Console.WriteLine($"firstDate={ firstDate}");
151+
//output:
152+
//firstDate = "2019-08-01T00:00:00"
153+
```
154+
155+
Using the low-level JSON reader/writer types
156+
```csharp
157+
using System;
158+
using System.IO;
159+
using System.Text;
160+
using System.Text.Json;
161+
162+
var writerOptions = new JsonWriterOptions
163+
{
164+
Indented = true
165+
};
166+
167+
using var stream = new MemoryStream();
168+
using var writer = new Utf8JsonWriter(stream, writerOptions);
169+
170+
writer.WriteStartObject();
171+
writer.WriteString("date", DateTimeOffset.Parse("8/2/2023 9:00 AM"));
172+
writer.WriteNumber("temp", 42);
173+
writer.WriteEndObject();
174+
writer.Flush();
175+
176+
var jsonBytes = stream.ToArray();
177+
string json = Encoding.UTF8.GetString(jsonBytes);
178+
Console.WriteLine(json);
179+
// {
180+
// "date": "2023-08-02T09:00:00+00:00"
181+
// "temp": 42
182+
// }
183+
184+
var readerOptions = new JsonReaderOptions
185+
{
186+
AllowTrailingCommas = true,
187+
CommentHandling = JsonCommentHandling.Skip
188+
};
189+
var reader = new Utf8JsonReader(jsonBytes, readerOptions);
190+
191+
while (reader.Read())
192+
{
193+
Console.Write(reader.TokenType);
194+
195+
switch (reader.TokenType)
196+
{
197+
case JsonTokenType.PropertyName:
198+
case JsonTokenType.String:
199+
{
200+
string? text = reader.GetString();
201+
Console.Write(" ");
202+
Console.Write(text);
203+
break;
204+
}
205+
206+
case JsonTokenType.Number:
207+
{
208+
int intValue = reader.GetInt32();
209+
Console.Write(" ");
210+
Console.Write(intValue);
211+
break;
212+
}
213+
214+
// Other token types elided for brevity
215+
}
216+
Console.WriteLine();
217+
}
218+
// StartObject
219+
// PropertyName date
220+
// String 2023-08-02T09:00:00+00:00
221+
// PropertyName temp
222+
// Number 42
223+
// EndObject
224+
```
225+
226+
## Main Types
227+
228+
<!-- The main types provided in this library -->
229+
230+
The main types provided by this library are:
231+
232+
* `System.Text.Json.Utf8JsonWriter`
233+
* `System.Text.Json.Utf8JsonReader`
234+
* `System.Text.Json.JsonSerializer`
235+
* `System.Text.Json.JsonConverter`
236+
* `System.Text.Json.JsonDocument`
237+
* `System.Text.Json.Nodes.JsonNode`
238+
* `System.Text.Json.Serialization.Metadata.JsonTypeInfo`
239+
240+
## Addtional Documentation
241+
242+
* [Conceptual documentation](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/overview)
243+
* [API documentation](https://learn.microsoft.com/en-us/dotnet/api/system.text.json)
244+
245+
## Related Packages
246+
247+
<!-- The related packages associated with this package -->
248+
249+
* Lightweight data formats abstraction: [System.Memory.Data](https://www.nuget.org/packages/System.Memory.Data/)
250+
* Serialization of HttpContent: [System.Net.Http.Json](https://www.nuget.org/packages/System.Net.Http.Json/)
251+
252+
253+
## Feedback & Contributing
6254

7-
For more information, see the documentation:
255+
<!-- How to provide feedback on this package and contribute to it -->
8256

9-
- [JSON serialization and deserialization in .NET](https://docs.microsoft.com/dotnet/standard/serialization/system-text-json-overview)
10-
- [How to serialize and deserialize JSON in .NET](https://docs.microsoft.com/dotnet/standard/serialization/system-text-json-how-to)
11-
- [System.Text.Json API reference](https://docs.microsoft.com/dotnet/api/system.text.json)
257+
System.Text.Json is released as open source under the [MIT license](https://licenses.nuget.org/MIT). Bug reports and contributions are welcome at [the GitHub repository](https://github.com/dotnet/runtime).

0 commit comments

Comments
 (0)