0

I cannot succeed to deserialize JSON object passed from c# code behind. I have been working on this 3 hours and couldn't understand the reason.

Here is my 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 is jquery code which deserialize the 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 is this

 d: "[{"id":67,"name":"Kardiyoloji"},{"id":1,"name":"Acil Tip"}]"

I cannot deserialize the json object properly, please help me to do it?

4
  • 1
    But what is happening when you are deserializing ? is there any error message ? Commented Apr 5, 2013 at 8:04
  • What does the serialized json look like? (Run the api request in fiddler, and see what it returns) Commented Apr 5, 2013 at 8:04
  • I added the json object above. Sorry, I had the put it at the begining Commented Apr 5, 2013 at 8:04
  • 1
    d: "[{"id":67,"name":"Kardiyoloji"},{"id":1,"name":"Acil Tip"}]" Does not look like valid json to me. { d: [{"id":67,"name":"Kardiyoloji"},{"id":1,"name":"Acil Tip"}] } would be more appropriate Commented Apr 5, 2013 at 8:09

4 Answers 4

2

Your problem is (partly) because data.d is an array of objects, not a single object, so you can't access name and id properties of it to get useful information (it doesn't have any). I suspect what you should actually be doing is iterating over data.d, not data, like 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 from the server then there should be no need for you to parse it yourself. If you're returning a JSON object that has JSON string properties then you should change that since there's absolutely no need to do it that way.

Sign up to request clarification or add additional context in comments.

4 Comments

what you said makes sense but I am not sure how to do it. can you please give me a complete code?
@Borsel I'd need to know exactly what's being returned by the server; if you're using Firebug then you can see the response of AJAX requests in the Console, copy that and edit it into the question.
it returns this {"d":"[{\"id\":67,\"name\":\"Kardiyoloji\"},{\"id\":1,\"name\":\"Acil Tip\"}]"}
@Borsel Two options. 1. Change d from being a JSON string to actually being an array (essentially drop the double-quotes around it) - you'll likely need to change your server-side code to do that, however, and I can't help with that (I'm not a C#/ASP.NET programmer). 2. Parse the JSON string d to get the actual array, and then iterate over that; I've edited my answer to do that. Option 1 is the way you should really do it, but option 2 is easier to implement quickly.
1

Try this:

success: function (data) {
    $.each($.parseJSON(data.d), function (key, value) {
        $("#txt_speciality").tokenInput("add", {
            name: value.name,
            id: value.id
        });
    });
}

4 Comments

Ok, could you please show a sample json data?? may be just put a console.log(data) inside the success method. and paste the result here...
@Will.i.am Using console.log(data) won't be much help since the console display of an object/array doesn't usually match valid JSON structure. Ideally we want the string before it's parsed, not the resulting object.
{"d":"[{\"id\":67,\"name\":\"Kardiyoloji\"},{\"id\":1,\"name\":\"Acil Tip\"}]"}
this is the response from the server. I got this response from the chrome tool
0

I think your issue lies here:

$.each(data, function (dt) { // <----dt here
      var mydata = data.d; //<----data.d data here

Change to this:

success: function (data, status) {
   $.each(data, function (i, dt) {
      var mydata = dt.d;
      var obj = $.parseJSON(mydata);
      $("#txt_speciality").tokenInput("add", { name: obj.name, id: obj.id});
   });
 }

d: "[{"id":67,"name":"Kardiyoloji"},{"id":1,"name":"Acil Tip"}]"

Does not seem to be a valid json object to loop through.

1 Comment

That's because he is getting json encoded strings wrapped in " " which need to be parsed. Otherwise, well these are just strings.
0

You can try this:

success: function (data, status) {
           var mydata = $.parseJSON(data);           
           $.each(mydata, function (index, element) {
              $("#txt_speciality").tokenInput("add", { name: element.name, id: element.id});
           });
         }

If this works, the JSON content type is probably not set correctly.

1 Comment

this gives error Uncaught TypeError: Cannot read property 'length' of null

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.