Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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());
}
}