0

我的 WCF 服务返回了以下 JSON:

`{"DoWorkResult":[{"AAID":0,"AreaID":1,"AreaName":"Basement","AssemblyAssessmentID":1,"AssemblyID":493,"AssemblyName":"Handrail (Steel)","AssessmentID":1,"AssessmentName":"University Of WA","AttributesCount":1,"CapitalReplacementUnitCost":623,"CategoryID":7,"CategoryName":"Furniture and Fixtures","CountedUnits":7,"CreatedBy":"Admin","ElementID":37,"ElementName":"Handrails and Balustrades","FacilityID":1,"FacilityName":"Central Chilled Water Plant","FacilityPercentage":"0","IsCompleted":1,"IsHeritage":false,"IsSafetyRisk":false,"Level1Units":0,"Level2Units":0,"Level3Units":0,"Level4Units":0,"Level5Units":7,"MesurementUnit":"Items","PhotosCount":1,"RepairCost":0,"RepairNotes":"","RequiresSpecialist":false,"SiteName":"CRAWLEY","SpaceID":1,"SpaceName":"B01","TasksCount":0}]}

我的服务方式是这样的

[System.ServiceModel.OperationContract]   
    [WebInvoke(Method = "POST",
              BodyStyle = WebMessageBodyStyle.Wrapped,
              ResponseFormat = WebMessageFormat.Json,
              RequestFormat = WebMessageFormat.Json)]
    public List<BLL.BLL_AssemblyAssessment> DoWork(string id)   {


       return BLL.BLL_AssemblyAssessment.GetAssessemblyAssessmentByAssemblyAssessmentID(1, 1);

    }

我需要在 jquery ajax 成功中解析的数据。我如何将其解析为我班级的对象:

$.ajax({
            type: "POST",
            url: "MyTestService.svc/DoWork",
            data: '{"id":"3"}',
            processData: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
             alert(data);
            },
            error: function (msg) {
               // $("#errorDiv").text(msg);
               alert(msg);
            }
        });

}
4

3 回答 3

0

利用

  alert(JSON.parse(jsonString));
于 2013-02-20T08:49:53.690 回答
0

我真的没有看到问题。

由于您已将 JSON 指定为数据类型,因此 JSON 被解析为成功处理程序中的 javascript 对象。只需使用 $.each 对其进行迭代:

//data.DoWorkResult is an array with one element

$.each(data.DoWorkResult, function(k, v){
    alert(v.AAID); //will alert 0 one time since there is only one object in the
    //array and the value is 0 on the AAID property
});

小提琴

请注意,我需要在我的示例中解析 JSON,因为它不是由那里的任何 ajax 方法自动完成的。

于 2013-02-20T13:50:25.743 回答
0

在您的 javascript 代码中,$.ajax使用该选项调用该函数dataType: "json"让 jQuery 负责解析。

回调中的data变量success已经是一个 javascript 对象。

您可以访问其属性:

success: function(data) {
    var html = "",
        rows = data.DoWorkResult,
        lgth = rows.length,
        i, row;
    for ( i=0; i<lgth; i++ ){
        row = rows[i];
        html += "<tr><td>"+row.AAID+"</td><td>"+row.AreaName+"</td></tr>";
        // or whatever
    }

    $("#myTable").html( html );
}

据我了解,该类BLL.BLL_AssemblyAssessment是一个C#类,将在服务器端使用,而不是javascript在客户端使用。在 javascript 中,对象不需要类定义来保存数据。

您可以将对象输出到控制台以检查其结构:

success: function(data) {
    console.log(data);
    console.log(data.DoWorkResult);
    console.log(data.DoWorkResult[0]);
}
于 2013-02-20T13:40:38.657 回答