JSON-Study

什么是JSON?

  • JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式,目前使用特别广泛。
  • 采用完全独立于编程语言的文本格式来存储和表示数据。
  • 简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。
  • 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

在 JavaScript 语言中,一切都是对象。因此,任何JavaScript 支持的类型都可以通过 JSON 来表示,例如字符串、数字、对象、数组等。看看他的要求和语法格式:

  • 对象表示为键值对,数据由逗号分隔
  • 花括号保存对象
  • 方括号保存数组

JSON 键值对是用来保存 JavaScript 对象的一种方式,和 JavaScript 对象的写法也大同小异,键/值对组合中的键名写在前面并用双引号 “” 包裹,使用冒号 : 分隔,然后紧接着值:

{"name": "QinJiang"}
{"age": "3"}
{"sex": "男"}

JSON 和 JavaScript 对象互转

要实现从JSON字符串转换为JavaScript 对象,使用 JSON.parse() 方法:

var obj = JSON.parse('{"a": "Hello", "b": "World"}');
//结果是 {a: 'Hello', b: 'World'}

要实现从JavaScript 对象转换为JSON字符串,使用 JSON.stringify() 方法:

var json = JSON.stringify({a: 'Hello', b: 'World'});
//结果是 '{"a": "Hello", "b": "World"}'

Controller返回JSON

Jackson应该是目前比较好的json解析工具了

当然工具不止这一个,比如还有阿里巴巴的 fastjson 等等。

我们这里使用Jackson,使用它需要导入它的jar包;

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.9.8</version>
</dependency>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--1.注册servlet-->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <!-- 启动顺序,数字越小,启动越早 -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!--所有请求都会被springmvc拦截 -->
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/</url-pattern>
    </filter-mapping>
</web-app>

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <context:component-scan base-package="com.ice.controller"/>
    <mvc:default-servlet-handler />
    <mvc:annotation-driven />

    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

pojo.User

package com.ice.pojo;

/**
 * @author zph
 * @description TODO
 * @create 2021/10/24 16:43
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
    private String sex;
}

Controller

package com.ice.controller;
/**
 * @author zph
 * @description TODO
 * @create 2021/10/24 16:44
 */
@RestController
public class UserController {

    @RequestMapping("/t1")
    public String test() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        User user = new User("张三", 18, "nan");

        String str = mapper.writeValueAsString(user);
        return str;
    }

}

@RestController

类上注解,表示此Controller只会返回字符串类型

@ResponseBody

方法上,表示只返回字符串类型的数据

JSON乱码问题 统一解决

<!--    JSON 乱码问题-->
    <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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Traceback (most recent call last): File "D:\02-study\python_scripts\load\venv\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen httplib_response = self._make_request( File "D:\02-study\python_scripts\load\venv\lib\site-packages\urllib3\connectionpool.py", line 398, in _make_request conn.request(method, url, **httplib_request_kw) File "D:\02-study\python_scripts\load\venv\lib\site-packages\urllib3\connection.py", line 239, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File "D:\02-study\python\lib\http\client.py", line 1282, in request self._send_request(method, url, body, headers, encode_chunked) File "D:\02-study\python\lib\http\client.py", line 1328, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "D:\02-study\python\lib\http\client.py", line 1277, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "D:\02-study\python\lib\http\client.py", line 1037, in _send_output self.send(msg) File "D:\02-study\python\lib\http\client.py", line 975, in send self.connect() File "D:\02-study\python_scripts\load\venv\lib\site-packages\urllib3\connection.py", line 205, in connect conn = self._new_conn() File "D:\02-study\python_scripts\load\venv\lib\site-packages\urllib3\connection.py", line 186, in _new_conn raise NewConnectionError( urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x000001CC3180D4B0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\02-study\python_scripts\load\venv\lib\site-packages\requests\adapters.py", line 489, in send resp = conn.urlopen( File "D:\02-study\python_scripts\load\venv\lib\site-packages\urllib3\connectionpool.py", line 787, in urlopen retries = retries.increment( File "D:\02-study\python_scripts\load\venv\lib\site-packages\urllib3\util\retry.py", line 592, in increment raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='uem-uat.yun.hihonor.com', port=80): Max retries exceeded with url: /uem-gateway/analytics-metrics/services/user-access-detail/access-list/1/10?t=1679290718262 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001CC3180D4B0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\02-study\python_scripts\load\script\code_validate.py", line 61, in <module> res = q.query(role_code='China_Area#Country Representative') File "D:\02-study\python_scripts\load\script\code_validate.py", line 54, in query res = self.sess.request('post', url=url_pro, headers=header, json=json) File "D:\02-study\python_scripts\load\venv\lib\site-packages\requests\sessions.py", line 587, in request resp = self.send(prep, **send_kwargs) File "D:\02-study\python_scripts\load\venv\lib\site-packages\requests\sessions.py", line 701, in send r = adapter.send(request, **kwargs) File "D:\02-study\python_scripts\load\venv\lib\site-packages\requests\adapters.py", line 565, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='uem-uat.yun.hihonor.com', port=80): Max retries exceeded with url: /uem-gateway/analytics-metrics/services/user-access-detail/access-list/1/10?t=1679290718262 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001CC3180D4B0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))
04-19

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值