Serializing a list of Object using Json.NET

asp.net, c#

Solution

You should try this:

https://surajdeshpande.com/2013/10/01/json-net-examples/

string jsonString = JsonConvert.SerializeObject(userList);

Deserialize JSON to an Object:

JsonConvert.DeserializeObject<User>(jsonString);

Problem

I'm having a object model as below to which i'm binding data retrieving from the database. ``` public class Student { public virtual string serialNumber { set; get;} public virtual string studentFname { set; get;} public virtual string studentLname { set; get;} public virtual string studentAge { set; get;} } ``` There will be number of objects as there are multiple student data's so i should ideally bind the objects to a Collection preferably a LIST<> and my requirement is I should transport this list of object to another code(Android). I'm using Newtonsoft.Json and am trying to convert the object into json. But if I want to pass the list to another code i should convert the entire list as Json. Accordingly what should be my return type and how to serialize it for my code below ``` using Newtonsoft.Json; public class GetData { public List<Student> getData() { List<Student> stData = new List<Student>(); Student st = new Student(); string con = "Data Source=MK-001/PC; Initial Catalog=Inventory; Persist Security Info=True; User ID=sa; Password=sqlserver;"; using (SqlConnection myConnection = new SqlConnection(con)) { string query = "Select * from StudentData"; SqlCommand Cmd = new SqlCommand(query, myConnection); myConnection.Open(); using (SqlDataReader reader = Cmd.ExecuteReader()) { while (reader.Read()) { st.serialNumber = reader["Serial Number"].ToString(); st.studentFname = reader["Student Fname"].ToString(); st.studentLname = reader["Student Lname"].ToString(); st.studentAge = reader["Student Age"].ToString(); //Is this the correct way?? var jsonObject = JsonConvert.SerializeObject(set); stData.Add(jsonObject); } myConnection.Close(); } } //Im returning a list here. How to bind this to a json and what should be return type as per the change made? return stData; } } ```

Original source

Related problems