Bird
Raised Fist0

Given a JSON file people.json containing an array of Person objects, which code snippet correctly reads and deserializes it into a List<Person> in C#?

hard🚀 Application Q8 of Q15
C Sharp (C#) - File IO
Given a JSON file people.json containing an array of Person objects, which code snippet correctly reads and deserializes it into a List<Person> in C#?
Astring json = File.ReadAllText("people.json"); var people = JsonSerializer.Deserialize<List<Person>>(json);
Bvar people = JsonSerializer.Deserialize<Person[]>(File.ReadAllText("people.json"));
Cvar people = JsonSerializer.Deserialize<Person>(File.ReadAllText("people.json"));
Dvar people = JsonSerializer.Serialize<List<Person>>(File.ReadAllText("people.json"));
Step-by-Step Solution
Solution:
  1. Step 1: Read the JSON file content as a string

    Use File.ReadAllText to get the JSON text.
  2. Step 2: Deserialize into a List<Person>

    Use JsonSerializer.Deserialize<List<Person>>(json) to convert JSON array into a list of Person objects.
  3. Step 3: Analyze other options

    var people = JsonSerializer.Deserialize(File.ReadAllText("people.json")); deserializes into an array, which is valid but not a List. var people = JsonSerializer.Deserialize(File.ReadAllText("people.json")); tries to deserialize into a single Person object, which is incorrect for an array JSON. var people = JsonSerializer.Serialize>(File.ReadAllText("people.json")); incorrectly uses Serialize instead of Deserialize.
  4. Final Answer:

    string json = File.ReadAllText("people.json"); var people = JsonSerializer.Deserialize<List<Person>>(json); -> Option A
  5. Quick Check:

    Read file as string, then deserialize to List [OK]
Quick Trick: Read file text first, then deserialize to List [OK]
Common Mistakes:
MISTAKES
  • Deserializing directly to a single object instead of a collection
  • Using Serialize instead of Deserialize
  • Deserializing to array when List is required without conversion

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes