3

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;
    }
}
K C
  • 219
  • 1
  • 4
  • 19
  • return type should be string and the recipient side may construct it back as Json object or fill as List – codebased May 28 '14 at 07:02
  • so instead of var jsonObject = JsonConvert.SerializeObject(set); i should make it as string jsonObject =JsonConvert.SerializeObject(set)? – K C May 28 '14 at 07:04
  • Yes mate. http://surajdeshpande.wordpress.com/2013/10/01/json-net-examples/ – codebased May 28 '14 at 07:09
  • And even if i convert object value into a string, how can i handle the list of objects? – K C May 28 '14 at 07:11
  • The question is not clear - did you checked the link I gave you? – codebased May 28 '14 at 07:13
  • @ codebased thanks lot for the article provided It says a lot, but yes out of curiosity. If i convert the entire list as string, will i be able to access it with ease in another code(say Android)?.. Thanks – K C May 28 '14 at 07:13
  • Yes mate, mostly all platform provides you an option to read json as objects. – codebased May 28 '14 at 07:15
  • For android you will use: JSONObject jsonObject = new JSONObject(json); See this: http://stackoverflow.com/questions/9605913/how-to-parse-json-in-android – codebased May 28 '14 at 07:16
  • @codebased needless to say if i find the answer correct it would be a tick for sure :). But as your post are really helpful i would not hesitate to ask you this. Deserializing a string back to JSONObject looks fine from one of the link you provided, but in my case this string has a list of object values. So will i face any difficulty in getting all Student object values back from the list?? – K C May 28 '14 at 07:26
  • I mean the post looks perfect for just a single JSONObject, but what about the list of STudent Object in my case? – K C May 28 '14 at 07:33
  • It will not be a problem as the return would be an array for android – codebased May 28 '14 at 07:55

2 Answers2

10

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);
Pang
  • 9,564
  • 146
  • 81
  • 122
codebased
  • 6,945
  • 9
  • 50
  • 84
  • Thanks codebased, really helpful. People looking for the answer also go through the solution @Yuval provided. That is quite helpful too. – K C May 28 '14 at 07:45
  • 4
    Actually it should be `JsonConvert.DeserializeObject>(jsonString);` if you serialized a `List` – Alexander Pacha Apr 19 '17 at 21:43
  • The link is dead. This is why the answer should actually answer the question, instead of linking to an external page. – Corbie Jul 05 '23 at 13:06
3

You should serialize your List<Student> after you finish loading them from your DB;

string jsonObject = JsonConvert.SerializeObject(stData);

and return the json string from your method:

public string getData()
{  
     // Do stuff
     return jsonString // this is your List<Student> serialized to json
}

And on the other side, deserialize it back to a JSONObject:

JSONArray studentList = new JSONArray(studentJson);
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • @ Yuval thanks a lot for the answer. But as there are multiple student data in Database i may have to return a list of objects or as @Codebased said i should convert the entire list as string and return the string instead. But if i do so how will i deserialize the string back to object? – K C May 28 '14 at 07:19
  • Look at my code. I serialize stData which is a `List` and deserialize it on the other end – Yuval Itzchakov May 28 '14 at 07:20
  • I didn't notice your other side was android. Modified my code. – Yuval Itzchakov May 28 '14 at 07:24
  • Thanks a lot again. Really helpful answer, but deserializing seems as if it is creating Json object from the returned JsonString(which contains a list of Student object). But if it contains 100's of data objects how will this be handled on other side? Shouldn't it be converted back to list of JSONObject? – K C May 28 '14 at 07:29
  • I'm not really familiar with java types. Try a `JSONArray` maybe? – Yuval Itzchakov May 28 '14 at 07:37
  • I'm marking codebased answer as a answer as he provided post which may be helpful for newbies like me but needless to say even you answer is equally important...Thanks a lot – K C May 28 '14 at 07:43