c# - jQuery cannot deserialize json object properly -
i cannot succeed deserialize json object passed c# code behind. have been working on 3 hours , couldn't understand reason.
here json object creation
struct specialitiy_struct { public int id; public string name; }; [webmethod] public static string get_specialities(string professionalid) { database db = databasefactory.createdatabase("connection"); dbcommand dbcommand; dbcommand = db.getstoredproccommand("select_profes_speciality"); db.addinparameter(dbcommand, "prof_id", dbtype.int16, convert.toint16(professionalid)); idatareader dr = db.executereader(dbcommand); list<specialitiy_struct> my_list = new list<specialitiy_struct>(); specialitiy_struct my_speciality; while (dr.read()) { my_speciality = new specialitiy_struct(); my_speciality.id = convert.toint16(dr["specialtyid"].tostring().trim()); my_speciality.name = dr["specialtyname"].tostring().trim(); my_list.add(my_speciality); } javascriptserializer serializer = new javascriptserializer(); return serializer.serialize(my_list); }
and here jquery code deserialize json object
$.ajax({ type: "post", url: "notificationsettings.aspx/get_specialities", data: "{'professionalid':'" + <%= session["proflid"].tostring().trim() %> + "'}", contenttype: "application/json; charset=utf-8", datatype: "json", success: function (data, status) { $.each(data, function (dt) { var mydata = data.d; var obj = $.parsejson(mydata); $("#txt_speciality").tokeninput("add", { name: obj.name, id: obj.id}); }); } });
the returned json object this
d: "[{"id":67,"name":"kardiyoloji"},{"id":1,"name":"acil tip"}]"
i cannot deserialize json object properly, please me it?
your problem (partly) because data.d
array of objects, not single object, can't access name
, id
properties of useful information (it doesn't have any). suspect should doing iterating on data.d
, not data
, so:
var d = $.parsejson(data.d); $.each(d, function(index, dt) { $("#txt_speciality").tokeninput("add", { name: dt.name, id: dt.id}); });
if you're returning valid json server there should no need parse yourself. if you're returning json object has json string properties should change since there's absolutely no need way.
Comments
Post a Comment