0

I have the following class:

public class Student
{
    public int studentNumber;
    public string testWeek;
    public string topics;
}

I do some stuff to it, serialize it and save it in a file. It looks likes this:

[
  {
    "studentNumber": 1,
    "testWeek": "1",
    "topics": "5 & 8"
  },
  {
    "studentNumber": 2,
    "testWeek": "1",
    "topics": "5 & 8"
  },
  {
    "studentNumber": 3,
    "testWeek": "1",
    "topics": "5 & 8"
  },
  {
    "studentNumber": 4,
    "testWeek": "1",
    "topics": "5 & 8"
  },
  {
    "studentNumber": 5,
    "testWeek": "1",
    "topics": "5 & 8"
  }
]

Later I want to deserialize it so I can work on it again. I have this code

Student[] arr = new Student[numberOfStudentsInClass];
arr = JsonConvert.DeserializeObject<Student>(File.ReadAllText(_selectedClass))

Where _selectedClass is string containing the file name. But I am getting an error

Cannot convert WindowsFormApplicationsForm1.Form.Student to WindowsFormApplicationsForm1.Form.Student[]

2 Answers 2

4

You indicated in your JsonConvert.DeserializeObject that you are trying to deserialize to a single Student instance. Not an array. And there's no need to initialize the array in one statement and then assign it a value on another. And anyways, we generally use generic arrays these days.

Replace:

Student[] arr = new Student[numberOfStudentsInClass];
arr = JsonConvert.DeserializeObject<Student>(File.ReadAllText(_selectedClass))

With this:

List<Student> students = 
     JsonConvert.DeserializeObject<List<Student>>(File.ReadAllText(_selectedClass));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I'd previously been working on the data as an array but maybe as a list might be better. Time to start rewriting!
3

As the exception states, the method JsonConvert.DeserializeObject<Student> returns an object of type Student, while the variable arr is of type Student[] .so you can't assign the result of JsonConvert.DeserializeObject<Student> to arr.

you need to Deserialize your text to a List<Student> instead and call .ToArray if you want an array such as follows:

Student[] students = JsonConvert.DeserializeObject<List<Student>>(File.ReadAllText(_selectedClass)).ToArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.