In my project, our backend is sending student data in form of a JSON object. I've to create a model to inflate that data and a ViewModel to make it reactive. I'm using Communitytoolkit.MVVM. Data returned from the server looks like this:
[
{
"id": "6a49c6de7634f86e8cadcae2",
"firstName": "Suresh",
"lastName": "Oberoi",
"photo": "https://nagpur-s3-bucket.s3.amazonaws.com/Ss4KAD04Byb4SsmGr5kSOQ4S7XZRhQ.jpeg",
"graduated": false,
"coursesTaken": {
"id": "7a5cc6db90d9e78f630178ae",
"name": "Intro to DB",
"semester": "Fall 2020",
"teacher": {
"id": "7a5cc6db90d9e78f630178ae",
"firstName": "Chulbul",
"lastName": "Pandey",
"teacherImage": "chulbul.jpeg"
},
},
},
{ /* More documents in same pattern as above */ }
]
From this I've to create required models and ViewModels.
I've following questions:
Can I create a simple model containing something like so:
public class Student { public string Id {get, set}; public string firstName {get, set}; public string lastName {get, set}; public string photo {get set); public bool graduated {get, set}, List<Course) coursesTaken {get; set}; }- If yes, how can I bind the
Studentmodel with the viewmodel usingObservableCollection?
- If yes, how can I bind the
Your class definition doesn't match your Json data. The code
List<Course) coursesTaken {get; set};is a list while the json string is an object.If you want variable
coursesTakento be a list, you need to add[]outside of the inner json string.And you also need to check whether the variable
teacheris aListor a normal object. Make sure that the Json data is consistent with the actual defined data type, otherwise the data will not be parsed successfully.Assuming the Json data is like what I posted above, you can define the code like below:
Then you can use method
JsonConvert.DeserializeObject<List<Student>>(jsonstr);to convert the json toList<Student> StudentsList;Note:
Your code of
Studentis not in the right format.The property should been defined as follows:not