Bird
Raised Fist0

What is wrong with this code snippet that tries to write an object to a JSON file?

medium📝 Debug Q14 of Q15
C Sharp (C#) - File IO
What is wrong with this code snippet that tries to write an object to a JSON file?
using System.Text.Json;
using System.IO;

var person = new Person { Name = "Bob", Age = 25 };
File.WriteAllText("person.json", person.ToString());

public class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}
AFile.WriteAllText cannot write to JSON files
BPerson class must be static to serialize
Cperson.ToString() does not convert the object to JSON format
DMissing using directive for System.IO
Step-by-Step Solution
Solution:
  1. Step 1: Analyze how object is converted to JSON

    Calling person.ToString() returns the class name, not JSON text.
  2. Step 2: Identify correct serialization method

    Use JsonSerializer.Serialize(person) to convert the object to JSON string before writing.
  3. Final Answer:

    person.ToString() does not convert the object to JSON format -> Option C
  4. Quick Check:

    To write JSON, serialize object first [OK]
Quick Trick: Use JsonSerializer.Serialize, not ToString(), to get JSON [OK]
Common Mistakes:
MISTAKES
  • Using ToString() instead of serialization
  • Assuming WriteAllText can't write JSON
  • Thinking class must be static to serialize

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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