vb381
vb381

Reputation: 181

JAVA - How to convert object to list

I have method that is setting variable as an object

Object value = response.getBody().jsonPath.get(variable)

returned object is in the following format

[{text1=value1, text2=value2, text3=value3}, {text1=value4, text2=value5, text3=value6}]

I need somehow to itter over this end verify all values (value1-6). How can I do that?

Upvotes: 0

Views: 3099

Answers (1)

Nayanish Damania
Nayanish Damania

Reputation: 652

MyClass.java

public class MyClass {
    private String text1;
    private String text2;

    public MyClass() {
    }

    public MyClass(String text1, String text2) {
        this.text1 = text1;
        this.text2 = text2;
    }

    public String getText1() {
        return this.text1;
    }

    public void setText1(String text1) {
        this.text1 = text1;
    }

    public String getText2() {
        return this.text2;
    }

    public void setText1(String text2) {
        this.text2 = text2;
    }
}
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();

String jsonInput = response.getBody();
List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});

Explanation of How ObjectMapper works:

The Jackson ObjectMapper class is the simplest way to parse JSON with Jackson. The Jackson Object mapper can parse JSON into objects of classes developed by you, or into objects of the built-in JSON tree model. The reason it is called ObjectMapper is that it maps JSON into Java Objects (deserialization), or Java Objects into JSON (serialization).

Upvotes: 1

Related Questions