我有一个如下所示的对象模型:
public class MyObjectModel
{
public int1 {get;set;}
public int2 {get;set;}
[ScriptIgnore]
public int3 {get;set;}
}
在我的代码中,我写了这个:
MyObjectModel TheObject = new MyObjectModel();
TheObject = LoadFromQuery(); //populates the properties using a linq-to-sql query
JavaScriptSerializer MyObjectSerializer = new JavaScriptSerializer();
string TheObjectInJson = MyObjectSerializer.Serialize(TheObject);
当我查看json字符串TheObjectInJson时,它看起来像这样:
"{\"int1\":31,\"int2\":5436}"
序列化程序为每个属性添加反斜杠。我尝试添加和删除类定义上方的[Serializable]属性,但无济于事。
为什么会发生这种情况的任何建议?
感谢。
答案 0 :(得分:10)
那应该是正确的。将JSON发送回浏览器时,所有属性名称必须用引号括起来。你看到的反斜杠是Visual Studio在查看字符串时转义字符串(我希望你在看到它时没有提到)。
如果您实际上将数据发送回电线,则应该将其视为
{"int1": 31, "int2":5436}
这是正确的JSON表示法。
有关JSON表示法的示例,请参阅Wikipedia。
答案 1 :(得分:0)
在控制器中,将对象的类型(不是字符串!)作为JsonResult返回,即:
[HttpGet]
public JsonResult<MyObjectModel> GetMyObject()
{
var theObject = LoadFromQuery(); //populates the properties (however)
return Json(theObject);
}