使用url中的get方法时,json中的怪异字符

时间:2019-03-18 08:24:01

标签: java json

RestTemplate restTemplate = new RestTemplate(); 
String response = restTemplate.getForObject(link, String.class);
JSONObject json = (JSONObject) new JSONParser().parse(response);
网址中的

json: {"description": "Explains how to construct 45° and 90°"}

json我得到: {"description": "Explains how to construct 45° and 90°"}

不带任何奇怪字符的任何获取实际json的帮助。

1 个答案:

答案 0 :(得分:2)

您只需要将StringHttpMessageConverter添加到模板的消息转换器中:

    RestTemplate restTemplate = new RestTemplate(); 
String response = restTemplate.getForObject(link, String.class);
    restTemplate.getMessageConverters()
            .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
JSONObject json = (JSONObject) new JSONParser().parse(response);

这里的主要代码是

restTemplate.getMessageConverters()
                .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));

它将邮件转换为 UTF-8

进口:

import org.springframework.web.client.RestTemplate;
import java.nio.charset.Charset;

有关详细代码,请检查this my answer。它具有完整的代码

希望这可以解决您的问题

谢谢:)