从JSON阅读,不显示数据 [英] Reading from JSON, data not displayed
问题描述
我有这个奇怪的问题。我retreve JSON字符串从URL像这样,
I'm having this strange problem when i try to access elements in json from javascript. i retreve a json string from a url like so,
// Create Request
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"www.someurl.com");
// Create Client
WebClient client = new WebClient();
// Assign Credentials
client.Credentials = new NetworkCredential("username", "pass");
// Grab Data
sjson = client.DownloadString(@"www.someurl.com");
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
oSerializer.MaxJsonLength = Int32.MaxValue;
sjson = oSerializer.Serialize(sjson);
但是,当我从JavaScript的HTML code访问此sjson变量,它不返回任何东西,但如果我硬code,它返回的值,请在这一个帮助。我试过很多东西,但没有奏效。我也试过,只是通过retreieved JSON字符串没有序列化,当我做到这一点的JavaScript停止工作。 :(以下是JavaScript code,
But when i access this sjson variable from javascript in html code, it doesn't return anything, but if i hard code it, it returns the values, please help on this one. I tried many things but didn't work. I also tried to just pass the retreieved json string without serializing, when i do that the javascript stops working. :( following is the javascript code,
<script type="text/javascript">
var jsons = JSON.parse('<%=sjson%>');
function initialize() {
alert("hahahahaaa");
document.writeln(jsons.Body[0].RowId.SensorIdValue);
//document.writeln(myobject.Body[0].RowId.SensorIdValue);
}
</script>
问题是
document.writeln(myobject.Body[0].RowId.SensorIdValue);
返回一个值,如果我使用MyObject的变量,但
returns a value if i use the myobject variable, but
document.writeln(jsons.Body[0].RowId.SensorIdValue);
返回没事的时候我与解析值使用。 :(
returns nothing when i use it with the parsed value. :(
以下是JSON输出(的Response.Write)通过C#运行后,序列化器我得到的样本,
following is the sample of the json output (response.write) i get after running the serializer via c#,
请帮我在这one..i不能似乎在这里找到问题。
Please help me on this one..i cant seem to find the problem here.
编辑:
如果它帮忙,fiollowing是JSON字符串我从服务器获取直不用其他作出任何序列化,
if it help, the fiollowing is the json string i get straight from the server witout making any serializations,
问题的很少的内容已被删除,由于业主要求
推荐答案
您不需要使用JSON序列化,因为远程服务器已返回一个JSON EN codeD字符串,你可以直接在页面中使用,避免双重编码。
You don't need to use a Json serializer because the remote server already returns a JSON encoded string that you could directly use in your page and avoid the double encoding.
所以:
public string GetJson()
{
// Create Client
using (WebClient client = new WebClient())
{
// Assign Credentials
client.Credentials = new NetworkCredential("username", "pass");
// Grab Data
return client.DownloadString(
@"www.someurl.com"
);
}
}
和则:
<script type="text/javascript">
var jsons = <%= GetJson() %>;
function initialize() {
alert("hahahahaaa");
document.writeln(jsons.Body[0].RowId.SensorIdValue);
//document.writeln(myobject.Body[0].RowId.SensorIdValue);
}
</script>
这篇关于从JSON阅读,不显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!