JsonConvert.SerializeObject没有将我的对象序列化为JSON字符串

时间:2017-10-06 19:53:42

标签: javascript json ajax asp.net-mvc

我正在使用Entity Framework和Database First方法。我想用来自数据库的数据填充我的饼图。该图表将显示在主页中,因此我在FillChart内创建了一个名为HomeController的方法。

的HomeController

public class HomeController : Controller
{
    private readonly IRoomRepository _roomRepository;

    public HomeController(IRoomRepository roomRepository)
    {
        _roomRepository = roomRepository;
    }

    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public ActionResult FillChart()
    {

        var dbRoomList = _roomRepository.GetAll().Select(x => new { x.DoorNumber, x.Fullness });
        var jsonString = JsonConvert.SerializeObject(dbRoomList.ToList());
        return Json(jsonString, JsonRequestBehavior.AllowGet);
    }
}

HTML

<canvas id="pieChart"></canvas>

的Javascript

<script type="text/javascript">
$(document).ready(function () {
    debugger;
    $.ajax({
        url: "FillChart",
        method: "GET",
        dataType: 'json',
        success: function (data) {
            debugger;
            console.log(JSON.parse(data));
            var doorNumber = [];
            var fullness = [];

            for (var i = 0; i < data.length; i++) {
                doorNumber.push("Door Number" + data[i].DoorNumber);
                fullness.push(data[i].Fullness);
            }

            var chartData = {

                labels: doorNumber,
                datasets: [{
                    label: 'Oda Numarası ',
                    borderColor: 'rgba(200, 200, 200, 0.75)',
                    hoverBorderColor: 'rgba(200, 200, 200, 1)',
                    data: fullness
                }]
            };

            var ctx = $("#pieChart");
            var barGraph = new Chart(ctx,
                {
                    type: 'pie',
                    data: chartData
                });
        },
        error: function (data) {

            console.log(data);
        },
    });
});

编译以下代码行后:

var jsonString = JsonConvert.SerializeObject(dbRoomList.ToList());

jsonString值似乎没有序列化:

"[{\"DoorNumber\":1,\"Fullness\":1},{\"DoorNumber\":2,\"Fullness\":0},{\"DoorNumber\":3,\"Fullness\":0},{\"DoorNumber\":4,\"Fullness\":0},{\"DoorNumber\":1,\"Fullness\":0}]"

但是当我用Text Visualizer查看jsonString的内部时,它看起来像这样:

[{"DoorNumber":1,"Fullness":1},{"DoorNumber":2,"Fullness":0},{"DoorNumber":3,"Fullness":0},{"DoorNumber":4,"Fullness":0},{"DoorNumber":1,"Fullness":0}]

我在调试模式下打开浏览器以检查javascript代码的变化

debugger

我看到data.lenght是151而不是5. console.log(JSON.parse(data));的结果是:

array

I have checked the answer of this question即使如此,我也无法找到解决问题的方法。我的代码有什么问题?

2 个答案:

答案 0 :(得分:1)

如果您从Controller返回Json(),则在发送之前不需要使用JsonConvert.SerializeObject()来序列化对象。 Controller.Json()方法将创建一个JsonResult对象,将指定对象序列化为JavaScript Object Notation(JSON)。

同样在您的jQuery代码中,由于您已将JSON指定为dataType,因此从服务器/ data回调中返回的success()预计会在JSON格式。您无需再次解析它。

服务器侧

[HttpGet]
public ActionResult FillChart()
{
    var dbRoomList = _roomRepository.GetAll()
        .Select(x => new { x.DoorNumber, x.Fullness });

    return Json(dbRoomList, JsonRequestBehavior.AllowGet);
}

jQuery代码

$.ajax({
    url: "FillChart",
    method: "GET",
    dataType: 'json',
    success: function (data) {
        // data should already be a JSON object

        var doorNumber = [];
        var fullness = [];

        for (var i = 0; i < data.length; i++) {
            doorNumber.push("Door Number" + data[i].DoorNumber);
            fullness.push(data[i].Fullness);
        }
       ...
    }
});

其他建议

我会将完全限定的url放在jQuery ajax url中。我也更喜欢使用Razor HTML helper来生成url,而不是手动将相对路径放在那里,因为有时相对url指向站点根而不是应用程序root。

例如,如果您将应用发布到服务器app1上名为www.example.com的文件夹中。您可以转到www.example.com/app1访问该应用。但是,/home/fillChart之类的任何相对网址实际上都会指向www.example.com/home/fillChart而不是www.example.com/app1/home/fillChart

所以我建议你这样做:

$.ajax({
    url: '@Url.Action("fillChart", "home", new { area = "" })',
    method: "GET",
    dataType: 'json',
    success: function (data) {
        // data should already be a JSON object

        var doorNumber = [];
        var fullness = [];

        for (var i = 0; i < data.length; i++) {
            doorNumber.push("Door Number" + data[i].DoorNumber);
            fullness.push(data[i].Fullness);
        }
       ...
    }
});

答案 1 :(得分:0)

151是原始json字符串的长度。

您永远不会将JSON.Parse结果设置为变量,然后遍历数组变量。

您需要在成功处理程序中执行此操作

    success: function (data) {
        debugger;
        var jsonArray = JSON.parse(data);
        console.log(jsonArray);
        var doorNumber = [];
        var fullness = [];

        for (var i = 0; i < jsonArray.length; i++) {
            doorNumber.push("Door Number" + data[i].DoorNumber);
            fullness.push(data[i].Fullness);
        }