1

I have a Javascript object like this:

var jsonDataActual = { 
                       "source": [{
                                    "name": "testCaption0", 
                                    "desc": "testDescrip0", 
                                    "values": [{ 
                                                 "from": "/Date(1338811241074)/", 
                                                   "to": "/Date(1346760041074)/", 
                                                "label": "testLabel0", 
                                          "customClass": "GanttRed"
                                               }] 
                                 }], 
                       "navigate": "scroll", 
                        "scale": "weeks", 
                        "maxScale": "months", 
                        "minScale": "days", 
                    "itemsPerPage": 11, 
                     "onItemClick": function (data) { }, 
                      "onAddClick": function (dt, rowId) { } 

                 };

it works fine for me. Now, because of my requirement and need, am making this entire object(including braces i.e.{ } and semicolon ;) as a string on server side (C#) and returning it to an ajax call (web Method) using a server side method:

in the server side method I do something like this:

return  new JavaScriptSerializer().Serialize(jsonData);

but now this entire returned data (inside Success: function(msg){ var s=msg.d} ) is treated as string, hence it doesn't work.

I tried these:

  1. var obj = eval('{' + msg.d +'}'); (removing beginning and ending braces in msg.d)
         typeof(obj) is string. failed

  2. eval('var obj ='+msg.d);  (including beginning and ending braces in msg.d)
         typeof(obj) is string. failed

  3. var obj= jQuery.parseJson(msg.d);
        typeof(obj) is string. failed
  4. var obj = new Object();
     //var obj = {}; 
      obj=jQuery.parseJson(msg.d).
      typeof(obj) is string. failed.

please help. How can I convert a server side returned json into object?

Why not is it working for me??. Is it because of structure of my json object??

and why does jsonDataActual works for me but not when sent as a string???

I saw this and this..

Please Help.....

Community
  • 1
  • 1
Manish Mishra
  • 12,163
  • 5
  • 35
  • 59

4 Answers4

2

found out solution to my specific problem.

I was constructing a string variable with my json data as its value. And then I would return this string to the client side function(the one making ajax request). i.e.

Server side method

[WebMethod]
public static string GetJsonData()
{
    string jsonData = String.Empty;
    foreach(var dataItem in objEntireData.Items)
    {
         //  jsonData +=  
    }
   return new JavaScriptSerializer().Serialize(result);
} 

but it was not working. So instead of constructing a string variable and serializing it, I wrote a class with specific structure and sent it in the return statement(after serialzing).

i.e. see below classes

    public class A
    {
        public A()
        {
            Values = new List<B>();
        }
        public string prop1 {get; set;}
        public List<B> Values { get; set; }
    }
    public class B
    {
        public string prop2 { get; set; }
        public string prop3 { get; set; }
    }

and I would use this class as below:

[WebMethod]
public static string GetJsonData()
{
          List<A> objA = new List<A>();
          A objAItem = new A();
          foreach (var dbItem in objDataBaseValues)
          {
                objA.prop1 = "test";
                B objBItem = new B();
                b.prop2="value";
                b.prop3="value";
                objA.Values.Add(objBItem);
          }
        return new JavaScriptSerializer().Serialize(objA);

  }

wrapping up my entire data into a class structure and then serializing this worked for me. my client side function successfully recognized it as an object i.e.

 $.ajax({
                    type: "POST",
                    url: "ProjectGanttChart.aspx/getData",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        var jsonData = jQuery.parseJSON(msg.d);
                        populateGantt(jsonData);
                     }
          }); 
Manish Mishra
  • 12,163
  • 5
  • 35
  • 59
0

try this

var json=(typeof msg.d) == 'string' ? eval('(' + msg.d + ')') : msg.d;
Ashirvad
  • 2,367
  • 1
  • 16
  • 20
0

I've run into this many times before. When a WCF service is decrypting the returned data into JSON, string data will always have " " around it. You should always return objects, or lists of objects from your WCF service - even if these are custom objects created at your service level.

So, your service should be, say:

[OperationContract]
        [WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/Test?testId={testId}", RequestFormat = WebMessageFormat.Json,
                   ResponseFormat = WebMessageFormat.Json)]
        List<TestObjectJSON> Test(int testId);

This will then do the deserialization for you on the service side, without using the Serializer.

Chris Dixon
  • 9,147
  • 5
  • 36
  • 68
  • @thexdixon..see am not using a WCF or a webservice. my method is simply kept on an aspx page. plane asp.net. – Manish Mishra Sep 04 '12 at 08:11
  • I'm not too sure how the parsing is done on a WebMethod, but if you're using .NET 4+, then I can imagine it being the same serialization as a service. Could you try doing the custom object approach quickly and seeing if that works? – Chris Dixon Sep 04 '12 at 08:26
0

How can I convert a server side returned json into object?

You can use JSON.parse to do that.

Example:

a = [1, 2];
x = JSON.stringify(a); // "[1,2]"
o = JSON.parse(x); // [1, 2];
Prasanth
  • 5,230
  • 2
  • 29
  • 61
  • god. even JSON.parse cudn't help. again I got string as a result of JSON.parse(msg.d) and not an object..goddd – Manish Mishra Sep 04 '12 at 08:10
  • what do you mean you want an object? you can put a string into a object using `var o = {"s":"string here"}; // now o.s = "string here"!` – Prasanth Sep 04 '12 at 08:15
  • wow...please read the question goldenparrot. Besides, var o={"s":"string here"}, is no use to me, I want "string here" to be an object and not it to be contained inside another object. i.e. "string here" has many keys and values inside it, i need to access them. i hope m making sense – Manish Mishra Sep 04 '12 at 08:22
  • Oh! My mistake. Btw, can you try: `var obj= jQuery.parseJson(jQuery.parseJson(msg.d));` – Prasanth Sep 04 '12 at 08:37