首页 > 解决方案 > 将 UNICODE 字符转换为通过 Spring MVC @ResponseBody 返回的 JSON 字符串中的 HTML 实体

问题描述

我正在编写一个 Spring MVC 应用程序,在其中我从 JSP 进行 AJAX 调用,该调用将返回一个 JSON 字符串。JSON 字符串中的某些文本会包含特殊字符,例如:

带有 unicode 8226 的项目符号字符或带有 unicode 8217 的撇号(引号)字符等标点字符

在我的 JSP 中,当我用这些字符填充文本区域时,它通常保持其原始形式并且显示良好。但是,我在应用程序的某些部分使用数据表编辑器,并且上述字符显示为?(问号)在网格中。

我想,解决方案是在形成 JSON 字符串时将 unicode 字符转换为 HTML 实体。例如,在控制器中,如果我扫描字符串中是否存在 8226 字符并将其替换为 • 并将此 JSON 字符串发送到 Datatables 网格,那么我可以正确看到项目符号字符。

我的问题是:在 Spring MVC 或其他工具中是否有任何方法可以检测大于 256 的 unicode 字符的存在,并在返回 JSON 字符串时将它们替换为 HTML 实体?在我的应用程序中有许多返回 JSON 字符串的 AJAX 调用,并且在每个@RequestMapping方法中调用转换工具都是一些工作。我在想是否有一个 Spring 拦截器可以进行这种转换。或者是否有任何策略ContentNegotiatingViewResolver来处理这种转换?

任何帮助表示赞赏。

这是我在我的映射@RestController

@RequestMapping(value = "/trips/{projectId}", method = RequestMethod.GET)
    public String getProjectTrips(@PathVariable BigInteger projectId) throws IOException {
        return projectTripReportGridService.getGridData(projectId);
    }

方法projectTripReportGridService.getGridData是:

public String getGridData(BigInteger projectId) throws IOException {

        List<ProjectTripReport> entityViews;

        entityViews = projectTripReportRepo.findAllByProjectId(projectId);

        for (ProjectTripReport si : entityViews) {
            if(si.getTripReport().indexOf(8226) > 0){
                StringBuilder sb = new StringBuilder();
                String tempReport = "";
                String wholeString = si.getTripReport();
                while(wholeString.indexOf(8226) > 0){
                    tempReport = wholeString.substring(0, wholeString.indexOf(8226));
                    sb.append(tempReport);
                    sb.append("&bull;");
                    wholeString = wholeString.substring(wholeString.indexOf(8226) + 1);
                }
                sb.append(wholeString);
                si.setTripReport(sb.toString());
            }
}
Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy[]{new OneToManyExclusionStrategy(), new JpaExclusionStrategy()}).create();
return gson.toJson(gson.toJsonTree(entityViews));
    }

标签: spring-mvcdatatables

解决方案


我知道我在我的问题中要问的是如何从应用程序的中心位置以 UTF-8 格式对 JSON 响应进行“编码”以获取“所有”JSON 响应字符串。下面是答案。springConfig.xml中需要添加如下脚本

<mvc:annotation-driven>
    <mvc:message-converters>
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8</value>
                <value>text/html;charset=UTF-8</value>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

推荐阅读