在Java中解析JSON数据 [英] Parsing JSON data in Java
问题描述
我想分析该网页上的一些数据:
http://www.bbc.co.uk /radio1/programmes/schedules/england/2013/03/1.json
I want to parse the some data from this page: http://www.bbc.co.uk/radio1/programmes/schedules/england/2013/03/1.json
我想分析的数据是不过标题我不确定我怎么能提取数据。这是我迄今所做的:
The data I want to parse is the titles however I am unsure how I can extract the data. This is what I have done so far:
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();
}
}
}
这只是返回null。谁能告诉我什么,我需要改变吗?谢谢你。
This just returns null. Can anybody tell me what I need to change? Thanks.
推荐答案
如果你读的JSONObject#GET(字符串)
的Javadoc,这实际上是 HashMap.get(字符串)
,它规定
If you read the javadoc of JSONObject#get(String)
which is actually HashMap.get(String)
, it states
返回:值以指定键映射,或无效如果
此映射包含的键的映射关系。
Returns: the value to which the specified key is mapped, or null if this map contains no mapping for the key
您JSON不包含该键的映射时间
。
Your JSON does not contain a mapping for the key time
.
编辑:
如果你的意思是标题
而不是时间
,以JSON的这种提取物
If you meant title
instead of time
, take this extract of the JSON
{"schedule":{"service":{"type":"radio","key":"radio1","title":"BBC Radio 1",...
您需要先获得进度
为的JSONObject
,那么服务
为的JSONObject
,然后标题
作为一个正常的字符串
值。应用此不同,这取决于JSON值的类型。
You need to first get schedule
as a JSONObject
, then service
as a JSONObject
, and then title
as a normal String
value. Apply this differently depending on the type of JSON value.
这篇关于在Java中解析JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!