UrlParams 转化成Json格式

在接收参数时 遇到了UrlParams格式的参数

goodName=%E6%9C%BA%E5%8A%A8%E8%BD%A6%E5%95%86%E4%B8%9A%E4%BF%9D%E9%99%A9&appliName=%E5%B0%8F%E7%8E%8B

发现这样转换后得出的JsonString 为:

 这样显然是不对的,需要进行转码,转码用下面这个方法:

requestParams = URLDecoder.decode(requestJsonString,"UTF-8");

转换后再得出的jsonString就正常了

 最后再附上将转码后的UrlParams 转化成JsonString的方法:

public static String getJsonStrByQueryUrl(String paramStr){
        String[] params = paramStr.split("&");
        JSONObject obj = new JSONObject();
        for (int i = 0; i < params.length; i++) {
            String[] param = params[i].split("=");
            if (param.length >= 2) {
                String key = param[0];
                String value = param[1];
                for (int j = 2; j < param.length; j++) {
                    value += "=" + param[j];
                }
                try {
                    obj.put(key,value);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return obj.toString();
    }
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 中使用 Thymeleaf 和 JSON 进行重定向可以通过以下步骤完成: 1. 在控制器中使用 `@ResponseBody` 注解将返回值换为 JSON 格式。 2. 使用 `RedirectAttributes` 将 JSON 数据添加到重定向的 URL 中。 3. 在 Thymeleaf 模板中使用 JavaScript 从重定向 URL 获取 JSON 数据并进行处理。 具体实现步骤如下: 1. 在控制器中使用 `@ResponseBody` 注解将返回值换为 JSON 格式: ```java @GetMapping("/json") @ResponseBody public Map<String, Object> json() { Map<String, Object> map = new HashMap<>(); map.put("username", "John"); map.put("age", 28); return map; } ``` 以上代码返回一个包含用户名和年龄的 JSON 对象。 2. 使用 `RedirectAttributes` 将 JSON 数据添加到重定向的 URL 中: ```java @GetMapping("/redirect") public String redirect(RedirectAttributes redirectAttributes) { Map<String, Object> map = new HashMap<>(); map.put("username", "John"); map.put("age", 28); redirectAttributes.addFlashAttribute("json", new Gson().toJson(map)); return "redirect:/result"; } ``` 以上代码将 JSON 对象添加到 Flash 属性中,并将其作为参数传递给重定向的 URL。 3. 在 Thymeleaf 模板中使用 JavaScript 从重定向 URL 获取 JSON 数据并进行处理: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>JSON Redirect</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script th:inline="javascript"> /*<![CDATA[*/ $(function() { var urlParams = new URLSearchParams(window.location.search); var json = urlParams.get('json'); var data = JSON.parse(decodeURIComponent(json)); console.log(data); }); /*]]>*/ </script> </head> <body> <h1>JSON Redirect</h1> </body> </html> ``` 以上代码使用 JavaScript 从重定向的 URL 获取 JSON 数据,并在控制台中输出数据。在实际应用中,可以根据需要进行处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值