Eri*_*ham 6 c# asp.net-mvc json jsonresult
上下文
语言:C#
平台版本:Microsoft .Net Framework 4.0
操作系统:Windows 7 Professional(64位)
约束:Microsoft MVC.Net 3.0
问题
我发现自己现在在浏览器中大量查看JSON,将浏览器指向一个Controller Action或我本地开发服务器上的另一个,并在视觉上解析JSON以确保所有内容都按照我们想要的方式进行格式化.MVC 3序列化程序(或JSON.Net序列化程序)返回的JSON总是返回一个缩小的字符串,所以我结束了这样的事情:
{"Bars":[{"Name":"Ghost Bar","Address":"2440 Victory Park Lane, 33rd Floor, Dallas, TX 75219","OpenDate":"\/Date(1208062800000)\/","Status":"Open"},{"Name":"M-Street Bar","Address":"5628 Sears Street, Dallas, TX 75206","OpenDate":"\/Date(1064811600000)\/","Status":"Closed"},{"Name":"Zephyr\u0027s Lounge","Address":"3520 Greenville Avenue, Dallas, TX 75206","OpenDate":"\/Date(981007200000)\/","Status":"Open"}]}
Run Code Online (Sandbox Code Playgroud)
问题
我真的想找到一种方法,至少在调试期间,让JsonResult被"美化",使它看起来更像这样:
{
"Bars": [
{
"Name": "Ghost Bar",
"Address": "2440 Victory Park Lane, 33rd Floor, Dallas, TX 75219",
"OpenDate": "\/Date(1208062800000)\/",
"Status": "Open"
},
{
"Name": "M-Street Bar",
"Address": "5628 Sears Street, Dallas, TX 75206",
"OpenDate": "\/Date(1064811600000)\/",
"Status": "Closed"
},
{
"Name": "Zephyr\u0027s Lounge",
"Address": "3520 Greenville Avenue, Dallas, TX 75206",
"OpenDate": "\/Date(981007200000)\/",
"Status": "Open"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我知道有几个 在线 工具可以让你粘贴和格式化JSON.这是一个额外的步骤,并花了我很多时间.我更喜欢程序化解决方案.我还希望能够通过配置或#if编译器指令打开/关闭它.
我已经对此进行了粗略的搜索,并在Stack Overflow上发表了这篇文章.但是,给出的代码示例非常不完整.还提供了几个链接,但它们似乎已经死了.
无论如何,我想找到一种从ActionResult中获取"美化"JSON的方法.任何帮助appredciated.
以下源代码将重现我给出的初始未经修饰的JSON字符串作为示例.随意复制/粘贴/编辑.
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
namespace PrettyJsonResult.Controllers
{
public class DefaultController : Controller
{
public JsonResult Index()
{
var foo = new Foo();
foo.Bars.Add(new Bar { Address = "2440 Victory Park Lane, 33rd Floor, Dallas, TX 75219", Name = "Ghost Bar", Status = "Open" });
foo.Bars.Add(new Bar { Address = "5628 Sears Street, Dallas, TX 75206", Name = "M-Street Bar", Status = "Closed" });
foo.Bars.Add(new Bar { Address = "3520 Greenville Avenue, Dallas, TX 75206", Name = "Zephyr's Lounge", Status = "Open" });
return Json(foo, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
}
}
public class Foo
{
public Foo()
{
Bars = new List<Bar>();
}
public List<Bar> Bars { get; set; }
}
public class Bar
{
public string Name { get; set; }
public string Address { get; set; }
public string Status { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
EBa*_*arr 15
答案不是很多,但是如果你将Json序列化器从内置的(JavaScriptSerializer)切换到Json.NET(除了这个问题有很多优点),你可以这样做:
JsonConvert.SerializeObject( myObjectDestinedForJSON, Formatting.Indented);
Run Code Online (Sandbox Code Playgroud)
有关设置的文档:http://james.newtonking.com/projects/json/help/
| 归档时间: |
|
| 查看次数: |
14104 次 |
| 最近记录: |