英文:
How to get JSON value from RestTemplate
问题
我想要从RestTemplate请求中检索JSON文件的值。不幸的是,我不知道如何继续。我正在使用以下方法:
RestTemplate restTemplate = new RestTemplate();
final String url = "http://localhost:3333/command/core/get-csrf-token";
public String getToken() {
String token = restTemplate.getForObject(url, String.class);
System.out.println(token);
return token;
}
我得到一个字符串作为输出 { "token": "myToken" }
是否可以直接检索JSON的值?
英文:
I would like to retrieve the value of a JSON file from a RestTemplate request. Unfortunately, I do not know how to proceed. I am using the following method:
RestTemplate restTemplate = new RestTemplate();
final String url = "http://localhost:3333/command/core/get-csrf-token";
public String getToken() {
String token = restTemplate.getForObject(url, String.class);
System.out.println(token);
return token;
I get a String as output {"token":"myToken"}
Is it possible to retrieve directly the value of the JSON?
答案1
得分: 3
Sure, here is the translated code snippet:
使用库(例如Jackson)解析JSON并获取token
字段。
String json = restTemplate.getForObject(url, String.class);
ObjectMapper mapper = new ObjectMapper();
return mapper.readTree(json).get("token").asText();
英文:
Parse the JSON with a library (e.g. Jackson) and grab the token
field.
String json = restTemplate.getForObject(url, String.class);
ObjectMapper mapper = new ObjectMapper();
return mapper.readTree(json).get("token").asText();
答案2
得分: 0
当你说 String.class
时,你正在请求 RestTemplate 将结果作为字符串返回。相反,你可以选择以下任一方式:
class TokenHolder {
String token;
}
TokenHolder holder = restTemplate.getForObject(url, TokenHolder.class);
holder.getToken();
或者
// 这是必要的,因为泛型类型擦除
private static final ParameterizedTypeReference<Map<String, String>> MAP_TYPE =
new ParameterizedTypeReference<Map<String, String>>() {};
Map<String, String> map = restTemplate.getForObject(url, MAP_TYPE);
map.get("token");
一般来说,“强类型” TokenHolder
更可取。Lombok 的 @Value
和全新的 Java Record 特性可以帮助创建这种类,减少样板代码。
英文:
When you say String.class
, you're asking RestTemplate to give you the result as a String. Instead, you can do either of these:
class TokenHolder {
String token;
}
TokenHolder holder = restTemplate.getForObject(url, TokenHolder.class);
holder.getToken();
or
// this is necessary because of generic type erasure
private static final ParameterizedTypeReference<Map<String, String>> MAP_TYPE =
new ParameterizedTypeReference<Map<String, String>>() {};
Map<String, String> map = restTemplate.getForObject(url, MAP);
map.get("token");
The "strong type" TokenHolder
is generally preferable. Lombok's @Value
and the brand-new Java Record feature can help create such classes with little boilerplate.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论