简体   繁体   English

ASP.NET MVC 3序列化为JSON

[英]ASP.NET MVC 3 Serializing to JSON

I've got an ICollection<T> of POCO like this: 我有一个像这样的POCO的ICollection<T>

public class SearchJsonModel
{
   public string label { get; set; }
   public string category { get; }
}

In my Razor view, i serialize it as follows: 在我的Razor视图中,我将其序列化如下:

<script type="text/javascript">
   var jsonArray = @Html.Raw(Json.Encode(Model));
</script>

But the output is this: 但输出是这样的:

var jsonArray = [
   {"category":"Names","label":"Joe"},
   {"category":"Names","label":"John"}
];

Which is causing problems because of the quotes around the properties. 由于属性周围的引号导致问题。

I need to access the properties of each JSON object, so I would expect it to be like this: 我需要访问每个JSON对象的属性,所以我希望它是这样的:

var jsonArray = [
   {category:"Names",label:"Joe"},
   {category:"Names",label:"John"}
];

That way i can do something like this: 这样我可以做这样的事情:

$.each(jsonArray, function(index, item) {
   var x = item.category;
});

What am i doing wrong? 我究竟做错了什么? Am i using the wrong method to encode? 我使用错误的方法编码?

This JSON is valid (checked in JSONLINT ). 此JSON有效(在JSONLINT中检查)。 The quotes should be there. 引号应该在那里。

You can get the category values like this without any problem 你可以毫无问题地获得这样的类别值

$(function(){
   var data=[
   {"category":"Names","label":"Joe"},
   {"category":"Names","label":"John"}
];

    $.each(data,function(index,item){
          alert(item.category);
    });        

});​

Sample http://jsfiddle.net/DKnBh/ 示例http://jsfiddle.net/DKnBh/

This is standard JSON and shouldn't cause a problem. 这是标准的JSON,不应该导致问题。

See here for more info: in JSON, Why is each name quoted? 有关详细信息,请参阅此处: 在JSON中,为什么引用每个名称? .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM