序列化包含数组的对象
本文关键字:对象 数组 包含 序列化 | 更新日期: 2023-09-27 18:00:02
这个问题已经由我自己解决了-
所以我正在尝试使用knockoutJS并测试映射插件,我在序列化包含和数组的对象时遇到了一些问题
下面是我的控制器和下面的javascript,我的问题是无论我尝试什么(你可以看到注释掉的尝试来修复),我都无法将子数组传递给javascript来显示子对象-{"id":5,"name":"Testing this works","children":"[{},{}]"}
就是所有传递的内容。
有人能给我指正确的方向,请
namespace TestingKnockout.Controllers
{
public class child
{
int id;
String name;
public child(int id, string name)
{
this.id = id;
this.name = name;
}
}
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public virtual string GetData()
{
List<child> childrenList = new List<child>(){
new child(2, "bob"),
new child(4, "dave")
};
var result = new
{
id=5,
name="Testing this works",
children = childrenList
//children = Newtonsoft.Json.JsonConvert.SerializeObject(childrenList)
//children = new{ id = 2, name = "bob" }
};
//String resultsToHighlightJSON = Newtonsoft.Json.JsonConvert.SerializeObject(childrenList);
//return resultsToHighlightJSON;
return new JavaScriptSerializer().Serialize(result);// +resultsToHighlightJSON;
}
}
}
这是我的javascript:
<script language="javascript" type="text/javascript">
var originalData = {
id: 1,
name: "Main",
children: []
};
var updatedData = {
id: 1,
name: "Main",
children: [{ id: 2, name: "bob" }, { id: 3, name: "ted"}]
};
function Child(id, name) {
this.id = ko.observable(id);
this.name = ko.observable(name);
}
var options = {
children: {
key: function (data) {
return ko.utils.unwrapObservable(data.id);
}
}
}
var viewModel = ko.mapping.fromJS(originalData, options);
viewModel.counter = 1;
viewModel.addChild = function () {
viewModel.children.push(new Child(++viewModel.counter, "new"));
};
viewModel.applyUpdate = function () {
var basePath="<%: Url.Content("~/") %>";
var url = basePath + 'Home/GetData/';
$.get(url, function (response) {
var Employee = $.parseJSON(response);
$("#EditLink").html("testing this out : " + Employee.children[1].name);
//ko.mapping.fromJS( updatedData,viewModel);
ko.mapping.fromJS( Employee,viewModel);
});
}
$(document).ready(function() {
ko.applyBindings(viewModel);
});
请在GetData()
函数中尝试此操作。
return Newtonsoft.Json.JsonConvert.SerializeObject(result);
我从来没有遇到过JSON.NET的任何问题,而且我知道它支持匿名类型。
public class child
{
public int id { get; set; }
public String name { get; set; }
public child(int id, string name)
{
this.id = id;
this.name = name;
}
}
我的错误是我没有设置公共属性