C# and .NET • Modern C# baseline
JSON Serialization and Input Validation
Use a serializer for JSON syntax and validate deserialized data as untrusted input.
System.Text.Json converts between JSON and .NET types. Successful deserialization does not prove that the values satisfy application rules or that required data is safe to use. Validate ranges, required fields, and authorization after parsing, and handle malformed input explicitly.
Key points
- Do not assemble JSON with string concatenation.
- Keep serializer options consistent across producers and consumers.
Example
using System.Text.Json;
var payload = new { id = 12, title = "Build safely" };
string json = JsonSerializer.Serialize(payload);
Console.WriteLine(json);
What to expect
{"id":12,"title":"Build safely"}
Practice exercise
Deserialize a record from JSON and reject an empty title before storing it.
Key idea: A parser verifies structure; domain validation decides whether data is acceptable.