【发布时间】:2013-12-09 12:23:32
【问题描述】:
我想从这个页面解析一些数据: http://www.bbc.co.uk/radio1/programmes/schedules/england/2013/03/1.json
我要解析的数据是标题,但我不确定如何提取数据。这是我到目前为止所做的:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Test
{
public Test() { }
public static void main(String[] args)
{
URL url;
HttpURLConnection connection = null;
InputStream is = null;
JSONParser parser = new JSONParser();
try
{
url = new URL("http://www.bbc.co.uk/radio1/programmes/schedules/england/2013/03/1.json");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
is = connection.getInputStream();
BufferedReader theReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String reply;
while ((reply = theReader.readLine()) != null)
{
System.out.println(reply);
Object obj = parser.parse(reply);
JSONObject jsonObject = (JSONObject) obj;
String title = (String) jsonObject.get("time");
System.out.println(title);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
这只是返回空值。谁能告诉我我需要改变什么?谢谢。
【问题讨论】:
-
您的 JSON 中似乎没有名称为
time的 JSON 对象。 -
对不起,这是我的错误,时间意味着标题
-
您还假设每一行都是有效的 json 对象。我不确定结果是如何从服务器返回的。但是,如果对象被拆分为多行(这是有效的 json),您的代码将会中断
-
名称为
title的 JSON 对象是嵌套的。您需要获取它之上的每个级别(包含它)才能检索它。