package actionjackson.alternative; import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.jayway.jsonpath.JsonPath; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.web.client.RestTemplate; import java.util.List; import java.util.Map; @SpringBootTest class BindingAlternativesApplicationTests { @Autowired RestTemplate restTemplate; @Test void mapToRequest() { var request = Map.of("key1", "value1", "key2", Map.of( "nested", List.of("value2", "value3"))); System.out.println(restTemplate.postForEntity("https://httpbin.org/post", request, String.class)); } @Test void wrapRequest() { Conference springIo = new Conference("Spring I/O"); System.out.println(restTemplate.postForEntity( "https://httpbin.org/post", Map.of("conference", springIo), String.class)); } record Conference(String name) { } @Test void responseToMap() { Map<String, Object> response = restTemplate.getForObject("https://httpbin.org/get", Map.class); System.out.println("response = " + response); System.out.println("User-Agent: " + ((Map<String, Object>) response.get("headers")).get("User-Agent")); } @Test void responseToNodeWithJsonPointer() { JsonNode response = restTemplate.getForObject("https://httpbin.org/get", JsonNode.class); // Note: this should be a static final field in production code JsonPointer headersPointer = JsonPointer.compile("/headers/User-Agent"); String agent = response.at(headersPointer).asText(); System.out.println("agent from pointer = " + agent); } @Test void responseToNodeWithJsonPath() { JsonNode response = restTemplate.getForObject("https://httpbin.org/get", JsonNode.class); // Note: this should be a static final field in production code JsonPath jsonPath = JsonPath.compile("$..User-Agent"); // to have this as returned type, you need the custom config from the main class!!! ArrayNode array = jsonPath.read(response); System.out.println("agent from path = " + array.get(0).asText()); } }