压扁一个复杂的JSON对象绑定MVC [英] Flattening a complex json object for mvc binding

查看:108
本文介绍了压扁一个复杂的JSON对象绑定MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器在这样的JSON格式

返回一个对象图到视图

 返回JSON(客户);

在认为我的JSON对象看起来像这样

  {
    名称:'乔',
    预算:{金额:500,花100}
}

哪个正确映射到我的客户对象:

 公共类客户
{
    公共字符串名称{;设置;}
    公共预算预算{获取;设置;}
}公共类预算
{
    公共小数金额{获取;设置;}
    公共小数花费{获取;设置;}
}

我想通过相同的JSON对象回到另一个方法与此签名的控制器上:

 公众的ActionResult方法(客户的客户)

当我这样做,客户的名字得到填充,但不是预算类,我才明白为什么,因为ModelBinder的期待是:{名称:'乔','Budget.Amount':500,'Budget.Spend':100 }

所以我要选择:
1.我可以返回JSON对象在它想要的格式,但我不知道怎么,因为你不能做到这一点:

 返回JSON(新{Budget.Amount = 500})


  1. 我可以拼合在客户端的JSON对象。是否有插件或方法来做到这一点?


解决方案

下面是一个对象转换为平板哈希函数

 功能扁平化(JSON){
    VAR NJ = {},
        走=功能(J){
            VAR JP;
            对于(j中VAR道具){
                JP = j的[道具]
                如果(jp.toString()===[对象的对象]){
                    走(JP);
                }其他{
                    NJ [道具] = JP;
                }
            }
        };
    走(JSON);
    返回NJ;
}

My controller is returning an object graph to the view in json format like this

return Json(customer);

On the view my json object looks like this

{
    Name: 'Joe',
    Budget: { Amount: 500, Spend: 100 }
}

Which maps correctly to my customer object:

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

I want to pass that same json object back to another method on the controller with this signature:

public ActionResult Method(Customer customer)

When I do this customer's name get populated but not the Budget class, which I understand why because the modelbinder is expecting this: {Name:'Joe','Budget.Amount':500,'Budget.Spend': 100}

So I have to options: 1. I can return the json object in the format it wants, but I don't know how because you can't do this:

return Json(new { Budget.Amount= 500})

  1. I can flatten the json object on the client side. Is there plugins or methods to do this?

解决方案

Here's a function that convert an object to a flat hash

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

这篇关于压扁一个复杂的JSON对象绑定MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆