我的 Controller 正在像这样以 json 格式将对象图返回给 View
return Json(customer);
在 View 中我的 json 对象看起来像这样
{
Name: 'Joe',
Budget: { Amount: 500, Spend: 100 }
}
哪个正确映射到我的客户对象:
public class Customer
{
public string Name {get;set;}
public Budget Budget{get;set;}
}
public class Budget
{
public decimal Amount{get;set;}
public decimal Spend{get;set;}
}
我想将同一个 json 对象传递回具有此签名的 Controller 上的另一个方法:
public ActionResult Method(Customer customer)
当我执行此操作时,会填充此客户的名称但不会填充 Budget 类,我理解这是为什么,因为 modelbinder 期望这样:{Name:'Joe','Budget.Amount':500,'Budget.Spend': 100
所以我必须选择: 1. 我可以以它想要的格式返回 json 对象,但我不知道怎么做,因为你不能这样做:
return Json(new { Budget.Amount= 500})
- 我可以在客户端扁平化 json 对象。是否有插件或方法可以做到这一点?
最佳答案
这是一个将对象转换为平面散列的函数
function flatten(json){
var nj = {},
walk = function(j){
var jp;
for(var prop in j){
jp = j[prop];
if(jp.toString() === "[object Object]"){
walk(jp);
}else{
nj[prop] = jp;
}
}
};
walk(json);
return nj;
}
关于javascript - 为 mvc 绑定(bind)展平复杂的 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2210437/