Java JSON:使用 JSON 数据创建网页
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22945416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON: Create a web page with JSON data
提问by Sid
Firstly, I am extremely new to JSON. I have been reading as much as I can on it. While I get the concept, implementing it is a different deal altogether for me.
首先,我对 JSON 非常陌生。我一直在尽可能多地阅读它。虽然我明白了这个概念,但实施它对我来说完全不同。
So, I have an app which reads and displays data from JSON web pages. For instance, I can extract the time that is being shown in this website: http://date.jsontest.com/
所以,我有一个从 JSON 网页读取和显示数据的应用程序。例如,我可以提取此网站中显示的时间:http: //date.jsontest.com/
Using the HTML from this website, I added the JSON Object to my HTML page in the following manner:
使用此网站中的 HTML,我通过以下方式将 JSON 对象添加到我的 HTML 页面:
<html>
<body>
<pre>
{
"score": "30-20"
}
</pre>
</body>
</html>
However, the app now throws a JSON exception everytime I try to retreive the score.
但是,现在每次我尝试检索分数时,该应用程序都会抛出一个 JSON 异常。
My question is, 'Is adding a JSON Object to the pre tag in an HTML page the correct way of creating a JSON Object on a web page?'
我的问题是,“将 JSON 对象添加到 HTML 页面中的 pre 标记是在网页上创建 JSON 对象的正确方法吗?”
If not, what is the correct way to do it?
如果没有,正确的做法是什么?
EDIT: This is is the code I am using in java to retrieve the JSON data:
编辑:这是我在 java 中用来检索 JSON 数据的代码:
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if(status==200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
//JSONArray timeline = new JSONArray(0);
JSONObject last = new JSONObject(data);
return last;
}
else{
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
return null;
}
The try statement:
try 语句:
try {
json = lastTweet();
return json.getString("time");
//return "Oh Well";
}
Thanks.
谢谢。
回答by Sunny Patel
Your application should send the Content-type: application/json
header and should only output the string representation of the data itself, so that your entire page is just:
您的应用程序应该发送Content-type: application/json
标头,并且应该只输出数据本身的字符串表示,这样您的整个页面就是:
{
"score": "30-20"
}
and nothing more. The examplethat you gave follows the same procedure if you check the response headers and view the source code of that page.
仅此而已。如果您检查响应标头并查看该页面的源代码,则您提供的示例遵循相同的过程。
The reason your parser is failing is because the page starts with <
, when the first non-whitespace character should be {
.
您的解析器失败的原因是页面以 开头<
,而第一个非空白字符应该是{
.
回答by vp_arth
Use something like this:
使用这样的东西:
response.setContentType("application/json");
PrintWriter out = response.getWriter();
String json = "{\"data\": \"test\"}";
out.print(json);
out.flush();
on your dataserver
在您的数据服务器上