zoukankan      html  css  js  c++  java
  • 响应Ajax请求的Json被中的”被转义成"

    问题描述-

    今天写了一些代码,功能大概前端发送Ajax请求,后端查询数据库后将结果数组封装成Json字符串格式返回页面。对Json的处理使用的类库为Jackson。

    后台代码无报错,控制台打印查询结果列表显示正常。

    页面无法正常解析Json,打开浏览器控制台查看response数据,显示json中的"被转义成了",导致错误。

     问题分析-

    数据库查询结果打印出来无异常,传递到前台时json有问题,说明问题出在将结果list处理成json这一步。遂查看处理代码

    ObjectMapper objectMapper=new ObjectMapper();
            String categoriesString=null;
            try {
                categoriesString=objectMapper.writeValueAsString(categories);
                System.out.println("MSG:[categorys/json]="+categories.toString());
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            resp.setContentType("application/json;charset=utf-8");
            objectMapper.writeValue(resp.getWriter(),categoriesString);

    其中MSG的打印也时正常,说明问题出现在这一句:

    objectMapper.writeValue(resp.getWriter(),categoriesString);

    问题解决-

    方法有二:其一时继续使用writeValueAsString转换成字符串后直接使用response流返回:

    categoriesString=objectMapper.writeValueAsString(categories);
    resp.setContentType("application/json;charset=utf-8");
    resp.getWriter().write(categoriesString);

    其二是不适用writeValueAsString转换字符串,直接调用方法writeValue,第二个参数传递list数组即可:

    resp.setContentType("application/json;charset=utf-8");
    objectMapper.writeValue(resp.getOutputStream(),categories);
  • 相关阅读:
    二进制位运算
    Leetcode 373. Find K Pairs with Smallest Sums
    priority_queue的用法
    Leetcode 110. Balanced Binary Tree
    Leetcode 104. Maximum Depth of Binary Tree
    Leetcode 111. Minimum Depth of Binary Tree
    Leetcode 64. Minimum Path Sum
    Leetcode 63. Unique Paths II
    经典的递归练习
    案例:java中的基本排序
  • 原文地址:https://www.cnblogs.com/YFEYI/p/13301864.html
Copyright © 2011-2022 走看看