ssharma
ssharma

Reputation: 941

How to convert RestAssured Response to Java List

[
{
    "tags": [],
    "id": "aaaaaaaaaaaa",
    "author": "admin",
    "type": "profile",
    "description": "",
    "name": "defaultProfile1",
    "display_name": "Default1"
},
{
    "tags": [],
    "id": "bbbbbbbbbbbbb",
    "author": "admin",
    "type": "profile",
    "description": "test profile",
    "name": "defaultProfile2",
    "display_name": "Default2"
}]

this is the response I get from a Get Request, How can I convert this Response to Java List so that I can perform Stream().filter on the list.

Upvotes: 1

Views: 2229

Answers (3)

Hassan Iqbal
Hassan Iqbal

Reputation: 49

Goto http://www.jsonschema2pojo.org/ and convert your JSON to Java class, it will automatically change JSON to Java POJOs and that you can use to get response, suppose your POJO Class name is PojoResponseClass

Gson g = new Gson();
    PojoResponseClass resObj = g.fromJson(response.asString(), PojoResponseClass.class); 

Upvotes: 1

Aman Kumar Soni
Aman Kumar Soni

Reputation: 53

To use stream().filter() first you need to convert JSON into POJO and then you can use object mapper provided from Jackson below is the dependency:-

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

To convert your JSON into POJO you can use below or you can name the class you want:-

public class Author {
public List<String> tags;
public String id;
public String author;
public String type;
public String description;
public String name;
@JsonProperty(value = "display_name")
public String displayName;

// getter - setter 

}

Finally, we have to create List of Author so that you can use stream there:-

List<Author> list = Arrays.asList(mapper.readValue(json, Author[].class));

In place of json you can put your response which you are getting from GET api. Now you have created your list of items from JSON. So you can now use streams.

Upvotes: 1

Fenio
Fenio

Reputation: 3635

What you have here is an Array of JSON Objects.

You can easily convert it to Java classes to use filter even more effectively.

Create a class called User Object which represents single JSON Object like this:

public class UserObject {
    public List<String> tags;
    public String id;
    public String author;
    public String type;
    public String description;
    public String name;
    @JsonProperty(value = "display_name")
    public String displayName;
}

Then, using JsonPath convert JSON to list of those objects:

    JsonPath path = JsonPath.from(json); //String or File
    List<UserObject> users = Arrays.asList(path.getObject(".", UserObject[].class));

Basically, you are mapping the JSON to UserObject[] array and transform it into List for stream processing.

The dot in path.getObject means "start with the root of JSON"

Upvotes: 1

Related Questions