js转json格式,并解决乱码问题

html里:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSON</title>
    <script>
        //js 中的对象
        var user={
            name:"小明",
            age:18,
            gender:"男"
        }
        console.log(user)

        //怎么把js对象装换成json对象:  不可以直接转换
        //1.js对象转换成JSON字符串,JSON.stringify转换成JSON字符串
        var str=JSON.stringify(user)
        console.log(str)
        // console.log(typeof(str))

        //2.把JSON字符串转换成JS对象,JSON.parse 把JSON字符串对象转换成js对象
        var obj=JSON.parse(str)
        console.log(typeof(obj))
        console.log(obj)



    </script>
</head>
<body>

</body>
</html>

controller层转换

@ResponseBody
    @RequestMapping("/json1")
    public String json1() throws JsonProcessingException {
        //要求: 将下面对象,返回成JSON数据
        //需要用到JSON格式转换的工具JackJSON,fastJson

        //1.创建一个jackson的对象映射器,用来解析数据
        ObjectMapper mapper=new ObjectMapper();
        //2.创建对象
        User user=new User("小明","女",18);
        //3.直接将我们的对象转换成JSON格式
        String str=mapper.writeValueAsString(user);
        System.out.println(str);

        //如果这里直接返回str,找的是StringMvc的视图解析器,@ResponseBody

        return str;
    }
   

用注解解决乱码问题:

 @ResponseBody
    @RequestMapping(value="/json2",produces = "application/json;charset=utf-8")
    public String json2() throws JsonProcessingException {
        ObjectMapper mapper=new ObjectMapper();

        User user=new User("小明","女",18);

        String str=mapper.writeValueAsString(user);
        System.out.println(str);

        return str;
    }

在springmvc中配置乱码相关信息

<mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

你可能感兴趣的:(js转json格式,并解决乱码问题)