从Url读取JSON java
我在从一个URL获取JSON时遇到问题。下面是代码。从Url读取JSON java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import com.google.gson.Gson;
public class Test_Application {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Gson gson = new Gson();
String json = readUrl("http://api.wunderground.com/api/57dd9039b81a9c21/conditions/q/CA/San_Francisco.json");
Page page = gson.fromJson(json, Page.class);
System.out.println(page.description);
System.out.println(page.language);
System.out.println(page.link);
System.out.println(page.title);
}
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
static class Page {
String title;
String link;
String description;
String language;
List<Item> items;
}
static class Item {
String title;
String link;
String description;
}
}
输出是:
null
null
null
null
我认为问题是,我有一个不恰当的类来读取数据。这是正确的吗?
感谢
编辑
网站返回如下:
{
"response": {
"version": "0.1",
"termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"conditions": 1
}
},
"current_observation": {
"image": {
"url": "http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",
"title": "Weather Underground",
"link": "http://www.wunderground.com"
},
"display_location": {
"full": "San Francisco, CA",
"city": "San Francisco",
"state": "CA",
"state_name": "California",
"country": "US",
"country_iso3166": "US",
"zip": "94101",
"latitude": "37.77500916",
"longitude": "-122.41825867",
"elevation": "47.00000000"
},
"observation_location": {
"full": "SOMA - Near Van Ness, San Francisco, California",
"city": "SOMA - Near Van Ness, San Francisco",
"state": "California",
"country": "US",
"country_iso3166": "US",
"latitude": "37.773285",
"longitude": "-122.417725",
"elevation": "49 ft"
},
"estimated": {
},
"station_id": "KCASANFR58",
"observation_time": "Last Updated on February 19, 7:08 AM PST",
"observation_time_rfc822": "Tue, 19 Feb 2013 07:08:18 -0800",
"observation_epoch": "1361286498",
"local_time_rfc822": "Tue, 19 Feb 2013 07:08:31 -0800",
"local_epoch": "1361286511",
"local_tz_short": "PST",
"local_tz_long": "America/Los_Angeles",
"local_tz_offset": "-0800",
"weather": "Mostly Cloudy",
"temperature_string": "47.9 F (8.8 C)",
"temp_f": 47.9,
"temp_c": 8.8,
"relative_humidity": "87%",
"wind_string": "From the SW at 4.0 MPH Gusting to 13.0 MPH",
"wind_dir": "SW",
"wind_degrees": 225,
"wind_mph": 4.0,
"wind_gust_mph": "13.0",
"wind_kph": 6.4,
"wind_gust_kph": "20.9",
"pressure_mb": "1012",
"pressure_in": "29.90",
"pressure_trend": "-",
"dewpoint_string": "44 F (7 C)",
"dewpoint_f": 44,
"dewpoint_c": 7,
"heat_index_string": "NA",
"heat_index_f": "NA",
"heat_index_c": "NA",
"windchill_string": "46 F (8 C)",
"windchill_f": "46",
"windchill_c": "8",
"feelslike_string": "46 F (8 C)",
"feelslike_f": "46",
"feelslike_c": "8",
"visibility_mi": "10.0",
"visibility_km": "16.1",
"solarradiation": "",
"UV": "0",
"precip_1hr_string": "0.00 in (0 mm)",
"precip_1hr_in": "0.00",
"precip_1hr_metric": " 0",
"precip_today_string": "0.02 in (1 mm)",
"precip_today_in": "0.02",
"precip_today_metric": "1",
"icon": "mostlycloudy",
"icon_url": "http://icons-ak.wxug.com/i/c/k/mostlycloudy.gif",
"forecast_url": "http://www.wunderground.com/US/CA/San_Francisco.html",
"history_url": "http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KCASANFR58",
"ob_url": "http://www.wunderground.com/cgi-bin/findweather/getForecast?query=37.773285,-122.417725"
}
}
更新代码
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import com.google.gson.Gson;
public class Test_Application {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Gson gson = new Gson();
String json = readUrl("http://api.wunderground.com/api/57dd9039b81a9c21/conditions/q/CA/San_Francisco.json");
// Page page = gson.fromJson(json, Page.class);
Response response = gson.fromJson(json, Response.class);
System.out.println(response.termsOfService);
System.out.println(response.version);
}
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
static class Response{
String version;
String termsOfService;
}
}
替代GSON存在:
这个片段可以帮助做通用解码器:
Map< String, Object > decoded =
gson.fromJson(data, new TypeToken< Map< String, Object>>() {}.getType());
下面的代码是一个特定解码器的开始:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import com.google.gson.Gson;
public class Test_Application
{
public static void main(
String[] args) throws Exception
{
Gson gson = new Gson();
String json = readUrl(
"http://api.wunderground.com/api/57dd9039b81a9c21/" +
"conditions/q/CA/San_Francisco.json");
System.out.println(json);
Map< String, Object > decoded =
gson.fromJson(
json,
new TypeToken< Map< String, Object>>() {}.getType());
System.out.println(decoded);
Answer answer = gson.fromJson(json, Answer.class);
System.out.println(answer.response.version);
System.out.println(answer.response.termsofService);
System.out.println(answer.response.features.get("conditions"));
System.out.println(answer.current_observation.image);
System.out.println(answer.current_observation.display_location);
}
static class Response
{
String version;
URL termsofService;
Map< String, String > features;
}
static class Observation
{
Map< String, String > image;
Map< String, String > display_location;
// TODO: complete me
}
static class Location
{
// TODO: complete me
}
static class Answer
{
Response response;
Observation current_observation;
Location display_location;
// TODO: complete me
}
在这种发展状态它返回:
{response={version=0.1, termsofService=http://www.wunderground.com/weather/api/d/terms.html, features={conditions=1.0}}, current_observation={image={url=http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png, title=Weather Underground, link=http://www.wunderground.com}, display_location={full=San Francisco, CA, city=San Francisco, state=CA, state_name=California, country=US, country_iso3166=US, zip=94101, latitude=37.77500916, longitude=-122.41825867, elevation=47.00000000}, observation_location={full=SOMA - Near Van Ness, San Francisco, California, city=SOMA - Near Van Ness, San Francisco, state=California, country=US, country_iso3166=US, latitude=37.773285, longitude=-122.417725, elevation=49 ft}, estimated={}, station_id=KCASANFR58, observation_time=Last Updated on February 19, 8:16 AM PST, observation_time_rfc822=Tue, 19 Feb 2013 08:16:18 -0800, observation_epoch=1361290578, local_time_rfc822=Tue, 19 Feb 2013 08:16:18 -0800, local_epoch=1361290578, local_tz_short=PST, local_tz_long=America/Los_Angeles, local_tz_offset=-0800, weather=Mostly Cloudy, temperature_string=48.7 F (9.3 C), temp_f=48.7, temp_c=9.3, relative_humidity=83%, wind_string=From the ESE at 1.0 MPH, wind_dir=ESE, wind_degrees=109.0, wind_mph=1.0, wind_gust_mph=0.0, wind_kph=1.6, wind_gust_kph=0.0, pressure_mb=1012, pressure_in=29.88, pressure_trend=-, dewpoint_string=44 F (7 C), dewpoint_f=44.0, dewpoint_c=7.0, heat_index_string=NA, heat_index_f=NA, heat_index_c=NA, windchill_string=49 F (9 C), windchill_f=49, windchill_c=9, feelslike_string=49 F (9 C), feelslike_f=49, feelslike_c=9, visibility_mi=10.0, visibility_km=16.1, solarradiation=, UV=0, precip_1hr_string=0.00 in (0 mm), precip_1hr_in=0.00, precip_1hr_metric= 0, precip_today_string=0.02 in (1 mm), precip_today_in=0.02, precip_today_metric=1, icon=mostlycloudy, icon_url=http://icons-ak.wxug.com/i/c/k/mostlycloudy.gif, forecast_url=http://www.wunderground.com/US/CA/San_Francisco.html, history_url=http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KCASANFR58, ob_url=http://www.wunderground.com/cgi-bin/findweather/getForecast?query=37.773285,-122.417725}}
0.1
http://www.wunderground.com/weather/api/d/terms.html
1
{url=http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png, title=Weather Underground, link=http://www.wunderground.com}
{full=San Francisco, CA, city=San Francisco, state=CA, state_name=California, country=US, country_iso3166=US, zip=94101, latitude=37.77500916, longitude=-122.41825867, elevation=47.00000000}
一旦我填写你指定的类,我应该能够访问数据的权利? – 2013-02-19 15:57:17
就像一个FYI(我只从其他WU JSON问题中知道)'Response'中的'features'实际上可以包含一堆东西,这就是为什么在我的Response中它是一个Map。我不知道可能性的完整列表;如果API文档中包含所有这些对象的列表,您还可以创建一个完整的'Features'对象。 – 2013-02-19 15:58:42
是的,但这很痛苦,如果您只想使用字段,带有自定义分析器的通用Map
你的问题是,你的POJO与你的JSON不匹配。
JSON表示一个对象,并且您的POJO需要匹配它。这里是什么看起来像一个开始(没有getter/setter方法公开所有领域只是为了让这个例子小):
class MyWUPojo {
public Response response;
// more after this that match the JSON
}
class Response {
public String version;
public String termsofservice;
public Map<String, Integer> features;
}
注意,一个需要注意的是,如果你只对部分感兴趣的 JSON响应,这就是你必须实现的。 Gson会默默地忽略你没有包含在你的POJO中的JSON的任何部分。
@downvoter,请问我有理由改善这篇文章? – 2013-02-19 15:28:50
网站返回什么? – 2013-02-19 15:29:15
P.S.我没有倒下。 – 2013-02-19 15:29:31