【发布时间】:2018-01-31 21:02:15
【问题描述】:
我得到了一个 rest api,它返回这个嵌套响应:
"latitude":37.8267,
"longitude":-122.4233,
"timezone":"America/Los_Angeles",
"minutely":{
"summary":"Clear for the hour.",
"icon":"clear-day",
"data":[
{
"time":1517431560,
"precipIntensity":0,
"precipProbability":0
},
{
"time":1517431620,
"precipIntensity":0,
"precipProbability":0
},
....
所以,我需要获取详细的天气预报并将其放到对象上。我用 getter 和 setter(未列出)制作了一个 HourlyWeather 类:
public class HourlyWeather {
String time;
String precipIntensity;
String precipProbability;
这是我用 java 实现的小黄瓜步骤:
@Given("^rest api$")
public void restApi() throws Throwable {
restApiUrl = "https://api.darksky.net/forecast/******"; // my api key
}
@And("^rest api parameters$")
public void restApiParameters() throws Throwable {
restApiUrl = restApiUrl + "/37.8267,-122.4233";
}
@When("^I \"([^\"]*)\" rest api execution result$")
public void iRestApiExecutionResult(String method) throws Throwable {
RestAssured.baseURI = restApiUrl;
RequestSpecification httpRequest = RestAssured.given(); response = httpRequest.request(Method.GET);
}
这是我的问题:我在这里使用放心来获取我的嵌套 JSON 的一部分(我需要)。我在这里做了一个 toString 转换。之后 - 我使用 GSON 反序列化我的字符串并创建一个包含所有每小时天气 json 键数据的 HourlyWeather[] 对象。有什么办法可以避免这种转换并简化我的代码?
@Then("^I should deserialize result just to know how to do that$")
public void iShouldDeserializeResultJustToKnowHowToDoThat() throws Throwable {
// get only part of my nested json
// I would like ot get this part as an array list of HourlyWeather.class objects, not
// as ArrayList of HashMaps, so this is String here
String stringOfRequiredJSON = response.jsonPath().getJsonObject("minutely.data").toString();
Gson gson = new Gson();
HourlyWeather[] hourlyWeatherForecast = gson.fromJson(stringOfRequiredJSON, HourlyWeather[].class);
printHourlyWeather(hourlyWeatherForecast);
}
谢谢!
【问题讨论】:
标签: java json gson rest-assured