OkHttpJackson

PHOTO EMBED

Tue Apr 05 2022 11:11:22 GMT+0000 (Coordinated Universal Time)

Saved by @oliversinz

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;

public class OkHttpJackson {

    public static void main(String[] args) throws Exception {

        // avoid creating several instances, should be singleton
        OkHttpClient client = new OkHttpClient();

        // creating a request object
        Request request = new Request.Builder()
                .url("https://api.quotable.io/random")
                .build();

        // Decode the ResponseBody with Jackson
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        ResponseBody responseBody = client.newCall(request).execute().body();
        Quote entity = objectMapper.readValue(responseBody.string(), Quote.class);
        System.out.println(entity.getAuthor());
        System.out.println(entity.getContent());

    }

}
content_copyCOPY