简体   繁体   English

在放心的情况下,如何获得大于指定值的值

[英]How do I get a value greater than a specified value in rest assured

I am a newbie to Rest-Assured api using Java. 我是使用Java的Rest-Assured api的新手。 I want to extract the number of days the temperature of a city is above 18 . 我想提取一个城市的温度高于18天的天数。 Using openweathermap.org. 使用openweathermap.org。

The url is api.openweathermap.org/data/2.5/forecast?q=Sydney&units=metric&appid={APP KEY} 网址为api.openweathermap.org/data/2.5/forecast?q=Sydney&units=metric&appid={APP KEY}

I get : 我得到:

{ "cod": "200", "message": 0.0067, "cnt": 40, "list": [ { "dt": 1557727200, "main": { "temp": 20.88, "temp_min": 20.88, "temp_max": 21.05, "pressure": 1025.56, "sea_level": 1025.56, "grnd_level": 1021.14, "humidity": 57, "temp_kf": -0.17 }, "weather": [ { "id": 803, "main": "Clouds", "description": "broken clouds", "icon": "04d" } ], "clouds": { "all": 55 }, "wind": { "speed": 3.45, "deg": 43.754 }, "sys": { "pod": "d" }, "dt_txt": "2019-05-13 06:00:00" }, { "dt": 1557738000, "main": { "temp": 18.45, "temp_min": 18.45, "temp_max": 18.58, "pressure": 1026.06, "sea_level": 1026.06, "grnd_level": 1021.28, "humidity": 73, "temp_kf": -0.13 }, "weather": [ { "id": 804, "main": "Clouds", "description": "overcast clouds", "icon": "04n" } ], "clouds": { "all": 100 }, "wind": { "speed": 3.84, "deg": 28.267 }, "sys": { "pod": "n" }, "dt_txt": "2019-05-13 09:00:00" }, { "dt": 1557759600, "main": { "temp": 14.31, "temp_min": 14.31, "temp_max": 14.35, "pressure": 1026.29, "sea_level": 1026.29, "grnd {“ cod”:“ 200”,“ message”:0.0067,“ cnt”:40,“ list”:[{“ dt”:1557727200,“ main”:{“ temp”:20.88,“ temp_min”:20.88, “ temp_max”:21.05,“压力”:1025.56,“ sea_level”:1025.56,“ grnd_level”:1021.14,“湿度”:57,“ temp_kf”:-0.17},“天气”:[{“ id”:803, “ main”:“ Clouds”,“ description”:“碎云”,“ icon”:“ 04d”}],“ clouds”:{“ all”:55},“ wind”:{“ speed”:3.45, “ deg”:43.754},“ sys”:{“ pod”:“ d”},“ dt_txt”:“ 2019-05-13 06:00:00”},{“ dt”:1557738000,“ main”: {“ temp”:18.45,“ temp_min”:18.45,“ temp_max”:18.58,“压力”:1026.06,“ sea_level”:1026.06,“ grnd_level”:102.28,“湿度”:73,“ temp_kf”:-0.13} ,“天气”:[{“ id”:804,“ main”:“云”,“描述”:“阴云”,“ icon”:“ 04n”}],“云”:{“所有”:100 },“ wind”:{“ speed”:3.84,“ deg”:28.267},“ sys”:{“ pod”:“ n”},“ dt_txt”:“ 2019-05-13 09:00:00” },{“ dt”:1557759600,“ main”:{“ temp”:14.31,“ temp_min”:14.31,“ temp_max”:14.35,“ pressure”:1026.29,“ sea_level”:1026.29,“ grnd _level": 1021.87, "humidity": 80, "temp_kf": -0.04 }, "weather": [ { "id": 802, "main": "Clouds", "description": "scattered clouds", "icon": "03n" } ], "clouds": { "all": 28 }, "wind": { "speed": 1.66, "deg": 279.19 }, "sys": { "pod": "n" }, "dt_txt": "2019-05-13 15:00:00" }, _level”:102.87,“湿度”:80,“ temp_kf”:-0.04},“天气”:[{“ id”:802,“主”:“云”,“描述”:“散云”,“图标“:” 03n“}],” clouds“:{” all“:28},” wind“:{” speed“:1.66,” deg“:279.19},” sys“:{” pod“:” n“ },“ dt_txt”:“ 2019-05-13 15:00:00”},

} }

I am unsure how do i proceed with the iterations. 我不确定如何进行迭代。 It would be a great help if someone can help me through. 如果有人可以帮助我,那将是一个很大的帮助。

I am able to get the data but not sure how do I get the element from each array 我能够获取数据,但不确定如何从每个数组中获取元素

Now, I want to extract the temperatures which are above 18 degrees 现在,我要提取高于18度的温度

I have attempted the below: 我尝试了以下方法:


public class WeatherForecast {

    public static Response resp;

    @Test
    public void getWeatherForecastForCity()
    {
        RestAssured.baseURI = "https://api.openweathermap.org";



        resp = given().
               param("q", "Sydney").
               param("units", "metric").
               param("appid", "670473f82ba0969a884be548c75236a4").
        when().
                get("/data/2.5/forecast").
        then().
                extract().response();

        List<String> temperatures = resp.getBody().jsonPath().getList("list");
        //String value = temperatures.getString()
        int count = temperatures.size();
        for(int i=0;i<=count;i++)

        {

        }
        System.out.println("List Size: "+temperatures.size());

        //assertEquals(temperatures, greaterThanOrEqualTo(20.00F));

        //String responseString = resp.asString();
        //System.out.println("Response String: "+responseString);
        //JsonPath js = new JsonPath(responseString);

        //Get the number of records for the city
        //int size = js.getList("list").size();
        //int temperature = Integer.parseInt(js.get("count"));
        //System.out.println("Temperature Value: "+js.getString("list[1].main.temp"));

    }

}

RestAssured uses a powerful library called JsonPath which you already used. RestAssured使用一个功能强大的库JsonPath ,您已经在使用它。

The difference of what you already creates is how to get JSONObject/Array inside other JSONObject/Array 您已经创建的区别是如何在其他JSONObject / Array中获取JSONObject / Array

You used resp.getBody().jsonPath().getList("list"); 您使用了resp.getBody().jsonPath().getList("list"); which is almost a good starting point. 这几乎是一个很好的起点。 Instead of using List<String> you should use List<HashMap<String, Object>> 而不是使用List<String> ,应该使用List<HashMap<String, Object>>

Each HashMap<> will be a JSON Object. 每个HashMap<>将是一个JSON对象。

Then you can just iterate over the Array to get each object and temperatures. 然后,您可以遍历数组以获取每个对象和温度。

How to do that: 怎么做:

List<HashMap<String, Object>> list = resp.getBody().jsonPath().getList("list");
for (HashMap<String, Object> jsonObject : list) {
    /**
    * Now, in order to get temperature, we have to get access to `main` element in JSON and then get access to the temperature
    **/
    HashMap<String, Object> mainElements = (HashMap<String, Object>) jsonObject.get("main");
    //No we have JSONObject as HashMap. We can access any temperature
    float temperature = (float) mainElements.get("temp");
    System.out.println(temperature);
}

The above code will print all temperatures. 上面的代码将打印所有温度。 Now you just have to compare float values, save them, assert them or do whatever you want :) 现在,您只需要比较float值,保存它们,声明它们或执行任何您想做的事情即可:)

You can access any value with this approach 您可以使用此方法访问任何值

EDIT: Extract the above code to a method like this: 编辑:将上面的代码提取到这样的方法:

    private List<HashMap<String, Object>> getJsonObjectsWithTempGreaterThan(JsonPath path, float degrees) {
        List<HashMap<String, Object>> desiredJsonObjects = new ArrayList<>();

        List<HashMap<String, Object>> list = path.getList("list");
        for (HashMap<String, Object> jsonObject : list) {
            HashMap<String, Object> mainElements = (HashMap<String, Object>) jsonObject.get("main");
            float temperature = (float) mainElements.get("temp");
            if (temperature > degrees) {
                desiredJsonObjects.add(jsonObject);
            }
        }

        return desiredJsonObjects;
    }

Above code will store each of JSON Object in a List and then return it. 上面的代码会将每个JSON对象存储在一个List中,然后返回它。 The list will contain JSON Objects with a temperature greater than degrees passed in the parameter. 该列表将包含温度高于参数传递的度数的JSON对象。

Then, you can access those elements like this: 然后,您可以像这样访问这些元素:

List<HashMap<String, Object>> objects = getJsonObjectsWithTempGreaterThan(path, 20);

This is our list of desired objects. 这是我们所需的对象列表。 If you just want the temperatures, all you have to do is: 如果您只是想要温度,您要做的就是:

for (HashMap<String, Object> jsonObject : objects) {
    HashMap<String, Object> mainElements = (HashMap<String, Object>) jsonObject.get("main");
    //No we have JSONObject as HashMap. We can access any temperature
    float temperature = (float) mainElements.get("temp");
    System.out.println(temperature);
}

This can be achieved much more easily and readable with Java Streams. 使用Java Streams可以更轻松地实现此目标,并且可读性强。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何让 Rest Assured 在我的 REST 响应中返回文本(非加密或流式传输)值? - How do I get Rest Assured to return the text (non-encrypted or streamed) value in my REST response? 如何获取包含“确保余地”中的空格并且是另一个键的子键的键的值? - How do I get the value of a key that contains a space in Rest Assured and is child of another key? 如果密钥在“确保放心/宁静”中包含空格,如何获得密钥的值? - How do I get the value of a key if it contains a space in Rest Assured / Serenity? response.jsonPath() 元素周围有方括号,如何检索字符串值? Rest 放心 - response.jsonPath() has square brackets around the element, how do I retrieve the string value? Rest Assured 安倍得不到放心的output值 - not abe to get rest-assured output value 如何读取浮点值并打印小于或大于该值的最接近的数字? - How do I read a floating point value and print the closest numbers less than or greater than that value? 如何验证 Json 中的响应值 Rest Assured - how to validate Json Response value in Rest Assured 如何在“确保放心”中通过字段值查找对象? - How to find an object by a field value in Rest Assured? 放心。 从另一个值中获取值 - Rest-assured. get value from another value 如何处理大于Float.MAX_VALUE的值的浮点值输入 - How do I handle floating point value inputs for values greater than Float.MAX_VALUE
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM