简体   繁体   English

无法访问JSON对象

[英]Can't access JSON object

I am using asp mvc and am returning a json object to my view, and I cannot seem to access any of the properties in the json. 我正在使用asp mvc并向我的视图返回一个json对象,但似乎无法访问json中的任何属性。 Here is my code. 这是我的代码。

In my Model I have: 在我的模型中,我有:

public string getJson()
{ 
    File a = new File();
    a.Name = "matt";
    a.Path = "c:/adsgadsg/sdagdsag";
    string json = new JavaScriptSerializer().Serialize(a);
    //json = "{\"Name\":\"matt\",\"Path\":\"c:/adsgadsg/sdagdsag\"}"   
    return json;
}

Then in my javascript I have: 然后在我的JavaScript中,我有:

function test() {
    var userRegion = '@Model.getJson()';
    var tmp = userRegion.Name;
    var tmp2 = userRegion[0].Name;
    alert(tmp);//undefined
    alert(tmp2);//undefined
}

What am I doing wrong? 我究竟做错了什么? thanks. 谢谢。

EDIT: When I am debugging the javascript, I notice that '@Model.getJson()'; 编辑:当我调试javascript时,我注意到'@ Model.getJson()'; gets converted to a weird string that CANNOT be parsed by JSON.parse without an exception. 被转换为JSON.parse无法毫无例外地解析的奇怪字符串。

 var userRegion = JSON.parse('{"Name":"matt","Path":"c:/adsgadsg/sdagdsag"}');

Causes the exception Uncaught SyntaxError: Unexpected token & 导致异常Uncaught SyntaxError:意外的令牌&

You should first parse the JSON string to a Javascript object. 您应该首先将JSON字符串解析为Javascript对象。 This can be safely done for example with the Json2 library. 例如,可以使用Json2库安全地完成此操作。

UPDATE: Also, you should use the Html.Raw function to print out the JSON string, because other way it will be HTML encoded (quotation mark will become ", etc.). 更新:另外,您应该使用Html.Raw函数打印出JSON字符串,因为以其他方式将其编码为HTML(引号将变为“,等等”)。

Your code should look like this: 您的代码应如下所示:

function test() {
    var userRegion = JSON.parse('@Html.Raw(Model.getJson())');
    var tmp = userRegion.Name;
    //var tmp2 = userRegion[0].Name; this one is not correct
    alert(tmp);//undefined
    //alert(tmp2);//undefined
}

I am pretty sure that alert(userRegion ); 我很确定alert(userRegion ); return undefined . 返回undefined

Json can't serialize method and you have to move this code in property inside your model class. Json无法序列化方法,您必须在模型类的属性中移动此代码。

I'm using the following in MVC3: var events = JsonConvert.DeserializeObject>(yourObject); 我在MVC3中使用以下内容:var events = JsonConvert.DeserializeObject>(yourObject); Which will put the JSON string in the correct fields, and then I use a foreach loop to read from events, hope this will guide you in the correct direction. 它将JSON字符串放在正确的字段中,然后使用foreach循环从事件中读取数据,希望这将引导您朝正确的方向发展。

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

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