Java 将HttpResponse解析为自定义对象
我正在使用一些天气api,返回给定城市的实际天气预报。 我想将Java 将HttpResponse解析为自定义对象,java,json,Java,Json,我正在使用一些天气api,返回给定城市的实际天气预报。 我想将HtmlResponse解析到我的对象中,如下所示: public class Weather { String countryCode; String city; double temperature; double sensedTemperature; int humidity; int windSpeed; // meter/sec int windDirection;
HtmlResponse
解析到我的对象中,如下所示:
public class Weather {
String countryCode;
String city;
double temperature;
double sensedTemperature;
int humidity;
int windSpeed; // meter/sec
int windDirection;
int pressure;
int weatherDescription;
}
{
"visibility": 10000,
"timezone": 0,
"main": {
"temp": 7.21,
"temp_min": 5.56,
"humidity": 81,
"pressure": 1029,
"feels_like": 4.87,
"temp_max": 9
},
"clouds": {
"all": 75
},
"sys": {
"country": "GB",
"sunrise": 1577433953,
"sunset": 1577462200,
"id": 1414,
"type": 1
},
"dt": 1577444681,
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"icon": "04d",
"description": "broken clouds",
"main": "Clouds",
"id": 803
}
],
"name": "London",
"cod": 200,
"id": 2643743,
"base": "stations",
"wind": {
"speed": 1.5
}
}
JSONObject object = new JSONObject(response);
JSONObject windObject = new JSONObject(object);
String wind = windObject.getString("wind");
System.out.println(wind);
package weatherapp;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@RestController
public class WeatherController {
public static final String X_RAPID_HOST = "community-open-weather-map.p.rapidapi.com";
public static final String X_RAPIDAPI_KEY = "...";
public static final String CHARSET = "UTF-8";
public static final String HOST = "https://community-open-weather-map.p.rapidapi.com/weather";
//{city}/{lang}/{units]
@GetMapping("/weather")
public void getCurrentWeather(@RequestParam String city, @RequestParam(required = false) String lang,
@RequestParam(required = false) String units)
throws UnirestException, UnsupportedEncodingException {
//Params
String query = getQueryAccordingToGivenParameters(city, lang, units);
HttpResponse<JsonNode> response = Unirest.get(HOST + "?" + query)
.header("x-rapidapi-host", X_RAPID_HOST)
.header("x-rapidapi-key", X_RAPIDAPI_KEY)
.asJson();
JSONObject root = new JSONObject(response);
JSONObject wind = root.getJSONObject("wind");
double windSpeed = wind.getDouble("speed");
System.out.println(windSpeed);
}
...
}
执行整个操作的方法:
@GetMapping("/weather")
public void getCurrentWeather(@RequestParam String city, @RequestParam(required = false) String lang,
@RequestParam(required = false) String units)
throws UnirestException, UnsupportedEncodingException {
//Params
String query = getQueryAccordingToGivenParameters(city, lang, units);
HttpResponse<JsonNode> response = Unirest.get(HOST + "?" + query)
.header("x-rapidapi-host", X_RAPID_HOST)
.header("x-rapidapi-key", X_RAPIDAPI_KEY)
.asJson();
System.out.println(response.getBody());
}
我需要
“名称”-伦敦,
“风”-风速-1.5
“天气”-描述-“碎云”
“主”-温度-7.21
“主要”-湿度-81
还有其他一些,但这些只是例子
我尝试使用JSONObject
获得风速,如下所示:
public class Weather {
String countryCode;
String city;
double temperature;
double sensedTemperature;
int humidity;
int windSpeed; // meter/sec
int windDirection;
int pressure;
int weatherDescription;
}
{
"visibility": 10000,
"timezone": 0,
"main": {
"temp": 7.21,
"temp_min": 5.56,
"humidity": 81,
"pressure": 1029,
"feels_like": 4.87,
"temp_max": 9
},
"clouds": {
"all": 75
},
"sys": {
"country": "GB",
"sunrise": 1577433953,
"sunset": 1577462200,
"id": 1414,
"type": 1
},
"dt": 1577444681,
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"icon": "04d",
"description": "broken clouds",
"main": "Clouds",
"id": 803
}
],
"name": "London",
"cod": 200,
"id": 2643743,
"base": "stations",
"wind": {
"speed": 1.5
}
}
JSONObject object = new JSONObject(response);
JSONObject windObject = new JSONObject(object);
String wind = windObject.getString("wind");
System.out.println(wind);
package weatherapp;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@RestController
public class WeatherController {
public static final String X_RAPID_HOST = "community-open-weather-map.p.rapidapi.com";
public static final String X_RAPIDAPI_KEY = "...";
public static final String CHARSET = "UTF-8";
public static final String HOST = "https://community-open-weather-map.p.rapidapi.com/weather";
//{city}/{lang}/{units]
@GetMapping("/weather")
public void getCurrentWeather(@RequestParam String city, @RequestParam(required = false) String lang,
@RequestParam(required = false) String units)
throws UnirestException, UnsupportedEncodingException {
//Params
String query = getQueryAccordingToGivenParameters(city, lang, units);
HttpResponse<JsonNode> response = Unirest.get(HOST + "?" + query)
.header("x-rapidapi-host", X_RAPID_HOST)
.header("x-rapidapi-key", X_RAPIDAPI_KEY)
.asJson();
JSONObject root = new JSONObject(response);
JSONObject wind = root.getJSONObject("wind");
double windSpeed = wind.getDouble("speed");
System.out.println(windSpeed);
}
...
}
但是我得到了org.json.JSONException:JSONObject[“wind”]未找到。
你能告诉我如何测量风速和天气吗?其余的我应该自己做
//在Andreas中,答案代码如下所示:
public class Weather {
String countryCode;
String city;
double temperature;
double sensedTemperature;
int humidity;
int windSpeed; // meter/sec
int windDirection;
int pressure;
int weatherDescription;
}
{
"visibility": 10000,
"timezone": 0,
"main": {
"temp": 7.21,
"temp_min": 5.56,
"humidity": 81,
"pressure": 1029,
"feels_like": 4.87,
"temp_max": 9
},
"clouds": {
"all": 75
},
"sys": {
"country": "GB",
"sunrise": 1577433953,
"sunset": 1577462200,
"id": 1414,
"type": 1
},
"dt": 1577444681,
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"icon": "04d",
"description": "broken clouds",
"main": "Clouds",
"id": 803
}
],
"name": "London",
"cod": 200,
"id": 2643743,
"base": "stations",
"wind": {
"speed": 1.5
}
}
JSONObject object = new JSONObject(response);
JSONObject windObject = new JSONObject(object);
String wind = windObject.getString("wind");
System.out.println(wind);
package weatherapp;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@RestController
public class WeatherController {
public static final String X_RAPID_HOST = "community-open-weather-map.p.rapidapi.com";
public static final String X_RAPIDAPI_KEY = "...";
public static final String CHARSET = "UTF-8";
public static final String HOST = "https://community-open-weather-map.p.rapidapi.com/weather";
//{city}/{lang}/{units]
@GetMapping("/weather")
public void getCurrentWeather(@RequestParam String city, @RequestParam(required = false) String lang,
@RequestParam(required = false) String units)
throws UnirestException, UnsupportedEncodingException {
//Params
String query = getQueryAccordingToGivenParameters(city, lang, units);
HttpResponse<JsonNode> response = Unirest.get(HOST + "?" + query)
.header("x-rapidapi-host", X_RAPID_HOST)
.header("x-rapidapi-key", X_RAPIDAPI_KEY)
.asJson();
JSONObject root = new JSONObject(response);
JSONObject wind = root.getJSONObject("wind");
double windSpeed = wind.getDouble("speed");
System.out.println(windSpeed);
}
...
}
调试根目录后,如下所示:
更新
当您阅读正在使用的API的文档时,它确实很有帮助。提供以下javadoc的相关链接
由于response
是一个对象,因此需要调用以获取响应的主体,调用已解析的对象以获取根对象,调用以获取嵌套的wind
对象,最后调用以获取speed
值
JsonNode rootNode = response.getBody();
JSONObject rootObj = rootNode.getObject();
JSONObject windObj = rootObj.getJSONObject("wind");
double windSpeed = windObj.getDouble("speed");
您可以通过以下方式获取风速:
JSONObject json = new JSONObject(response);
JSONObject wind = json.getJSONObject("wind");
double speed = wind.getDouble("speed");
天气描述如下:
JSONObject json = new JSONObject(response);
JSONObject weather = json.getJSONArray("weather").getJSONObject(0);
String description = weather.getString("description");
您的json输出显示“wind”键是一个对象,您试图将wind作为字符串 用这个
JSONObject object = new JSONObject(response);
JSONObject windObject = object.getJSONObject("wind");
String speed = windObject.getString("speed");
System.out.println(speed);
我需要这样做:
HttpResponse<JsonNode> response = Unirest.get(HOST + "?" + query)
.header("x-rapidapi-host", X_RAPID_HOST)
.header("x-rapidapi-key", X_RAPIDAPI_KEY)
.asJson();
JSONObject z = response.getBody().getObject();
JSONObject zz = z.getJSONObject("wind");
double wind = zz.getDouble("speed");
HttpResponse response=Unirest.get(主机+“?”+查询)
.header(“x-rapidapi-host”,x\U RAPID\U host)
.header(“x-rapidapi-key”,x_-rapidapi_-key)
.asJson();
JSONObject z=response.getBody().getObject();
JSONObject zz=z.getJSONObject(“风”);
双风=zz.getDouble(“速度”);
您使用的是哪个JSON库JSONObject
可以是(Android),(JSON java),(JSON lib),…@Andreas import org.JSON.JSONObject;为什么在第2行用JSONObject
对象调用构造函数当wind
字段是JSON对象时,为什么要调用getString(“wind”)
{在:
之后?@Andreas是的,我现在知道了,你的答案看起来合乎逻辑,应该可以用,但它没有:“JsonNode
”是什么?如果Unirest
API已经将JSON解析为对象,为什么你要尝试使用另一个JSON API?使用你已经有的JSON API。它不起作用。我已经更新了问题wi这是您的答案。我在调试后为问题添加了root。