Manish Mishra
Manish Mishra

Reputation: 12375

Convert C# String into Javascript Object/JSON

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.....

Upvotes: 1

Views: 18469

Answers (4)

Manish Mishra
Manish Mishra

Reputation: 12375

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);
                     }
          }); 

Upvotes: 2

Prasanth
Prasanth

Reputation: 5258

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];

Upvotes: 0

Chris Dixon
Chris Dixon

Reputation: 9167

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.

Upvotes: 0

Ashirvad
Ashirvad

Reputation: 2377

try this

var json=(typeof msg.d) == 'string' ? eval('(' + msg.d + ')') : msg.d;

Upvotes: 0

Related Questions