将C#字符串转换为Javascript Object/JSON



我有一个类似这样的Javascript对象:

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

它对我来说很好。现在,由于我的要求和需要,我在服务器端(C#)将整个对象(包括大括号,即{}和分号;)作为字符串,并使用服务器端方法将其返回到ajax调用(web方法)

在服务器端方法中,我这样做:

return  new JavaScriptSerializer().Serialize(jsonData);

但是现在这个返回的全部数据(在Success: function(msg){ var s=msg.d}内部)被当作字符串处理,因此它不起作用。

我试过这些:

  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.

请帮忙。如何将服务器端返回的json转换为对象?

为什么它对我不起作用??。是因为我的json对象的结构吗??

为什么jsonDataActual对我有效,但作为字符串发送时无效???

我看到了这个和这个。。

请帮忙。。。。。

找到了我的特定问题的解决方案。

我构建了一个字符串变量,用json数据作为它的值。然后我将这个字符串返回给客户端函数(发出ajax请求的函数)。即

服务器端方法

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

但它不起作用。因此,我没有构造字符串变量并对其进行序列化,而是编写了一个具有特定结构的类,并在return语句中发送它(序列化后)。

即参见以下类别

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

我会使用这个类如下:

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

将我的整个数据封装到一个类结构中,然后对其进行序列化,这对我来说很有效。我的客户端函数成功地将其识别为一个对象,即

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

尝试这个

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

我以前多次遇到这种情况。当WCF服务将返回的数据解密为JSON时,字符串数据将始终包含"。您应该始终从WCF服务返回对象或对象列表,即使这些是在您的服务级别创建的自定义对象。

所以,你的服务应该是,比如:

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

然后,这将在服务端为您进行反序列化,而不使用序列化程序。

如何将服务器端返回的json转换为对象?

您可以使用JSON.parse来执行此操作。

示例:

a = [1, 2];
x = JSON.stringify(a); // "[1,2]"
o = JSON.parse(x); // [1, 2];

最新更新