MVC中返回Json的几种声明方式

第一种,单行数据

 
var result = new { name = "linfei", age = "26", address = "wuhan" };
//MVC中返回 return Json(result);
//asp.net中返回 System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); return js.Serialize(result);
 

显示结果:

{
    "name": "linfei",
    "age": "26",
    "address": "wuhan"
}

 

第二种,多行数据

 
var result = new object[] { new { name = "linfei", age = "22", address = "wuhan" }, new { name = "linfei", arg = "26", address = "sh" } };
//MVC中返回 return Json(result);
//asp.net中返回 System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); return js.Serialize(result);
 

显示结果:

 
[
    {
        "name": "linfei",
        "age": "22",
        "address": "wuhan"
    },
    {
        "name": "linfei",
        "arg": "26",
        "address": "sh"
    }
]
 

 

第三种,多行多对象数据

 
var data1 = new object[] { new { name = "linfei", age = "22", address = "wuhan" }, new { name = "linfei", arg = "26", address = "sh" } };
var data2 = new object[] { new { test="123",test1="qq"}, new { test = "456", test1 = "ww" } };
var result = new object[] { new { rows = data1 }, new { header = data2 } };
//MVC中返回
return Json(result);
//asp.net中返回
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
return js.Serialize(result);
 

 显示结果:

 
[
    {
        "rows": [
            {
                "name": "linfei",
                "age": "22",
                "address": "wuhan"
            },
            {
                "name": "linfei",
                "arg": "26",
                "address": "sh"
            }
        ]
    },
    {
        "header": [
            {
                "test": "123",
                "test1": "qq"
            },
            {
                "test": "456",
                "test1": "ww"
            }
        ]
    }
]
 

 

 还有个asp.net中的写法,网上找的

var data1 = new object[] { new { name = "linfei", age = "22", address = "wuhan" }, new { name = "linfei", arg = "26", address = "sh" } };
var data2 = new object[] { new { test = "123", test1 = "qq" }, new { test = "456", test1 = "ww" } };
Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
settings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
string result = Newtonsoft.Json.JsonConvert.SerializeObject(new { rows = data1, header = data2 }, Newtonsoft.Json.Formatting.Indented, settings);

 

posted @ 2013-05-19 03:06  AIの海雅  阅读(254)  评论(0编辑  收藏  举报