Consider the following C# code that serializes an object to JSON. What will be printed?
using System; using System.Text.Json; public class Person { public string Name { get; set; } public int Age { get; set; } } public class Program { public static void Main() { var person = new Person { Name = "Alice", Age = 30 }; string json = JsonSerializer.Serialize(person); Console.WriteLine(json); } }
Remember that property names are serialized with exact casing by default.
The JsonSerializer in C# serializes properties with their exact names and string values are quoted. So the output includes property names with uppercase first letters and string values in quotes.
What error will this code produce when trying to deserialize the JSON string?
using System; using System.Text.Json; public class Person { public string Name { get; set; } public int Age { get; set; } } public class Program { public static void Main() { string json = "{\"Name\":\"Bob\", \"Age\":\"thirty\"}"; var person = JsonSerializer.Deserialize<Person>(json); Console.WriteLine(person.Name); } }
Check the type of the 'Age' property and the JSON value type.
The JSON has the 'Age' property as a string "thirty" but the C# class expects an int. This causes a JsonException during deserialization.
Given this class and serialization code, why is the 'Password' property missing in the JSON output?
using System; using System.Text.Json; using System.Text.Json.Serialization; public class User { public string Username { get; set; } [JsonIgnore] public string Password { get; set; } } public class Program { public static void Main() { var user = new User { Username = "user1", Password = "secret" }; string json = JsonSerializer.Serialize(user); Console.WriteLine(json); } }
Look at the attributes above the Password property.
The [JsonIgnore] attribute instructs the serializer to exclude that property from the JSON output.
Given this JSON string and class, which code correctly deserializes the JSON?
{"full_name":"John Doe","Age":25}Class:
public class Person {
[JsonPropertyName("full_name")]
public string Name { get; set; }
public int Age { get; set; }
}The attribute [JsonPropertyName] maps JSON property names to class properties.
The [JsonPropertyName("full_name")] attribute tells the deserializer to map the JSON property 'full_name' to the Name property. So default deserialization works.
Given this JSON string and code, how many key-value pairs does the resulting dictionary contain?
{"a":1,"b":2,"c":3}Code:
using System;
using System.Text.Json;
using System.Collections.Generic;
public class Program {
public static void Main() {
string json = "{\"a\":1,\"b\":2,\"c\":3}";
var dict = JsonSerializer.Deserialize>(json);
Console.WriteLine(dict.Count);
}
} Count the number of properties in the JSON object.
The JSON object has three properties: 'a', 'b', and 'c'. Deserializing into a dictionary creates three entries.