Json代码实战演练

Json代码实战演练


Json是什么

Json是一种数据交换格式,完全独立于编程语言的文本格式,有一套标准的语法规则,便于机器解析。

为什么用Json

可读性、可拓展性强、编写难度低;作为统一的数据文本格式在不同平台间规范数据格式。

怎么用Json

在JS中,Json文本能被解析为对象;对象也可解析为Json文本。

在SpringMVC中,添加了@RestController/@Responsebody的控制器能将返回对象解析为Json文本;添加了@RequestBody能将请求体中Json文本解析为对应对象。

若对SpringMVC自动解析需求不满,可通过定义自定义方法参数解析器HandlerMethodArgumentResolver,通过RequestMappingHandlerAdapter注入请求映射处理器中执行,完成对请求体Json文本转换为方法参数对象。

自定义方法参数解析器:

参数解析器编写:

import com.myProject.filter.RequestWrapper;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class JsonArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JsonRequestBody.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        // Json请求体,RequestWrapper为在过滤器中对原生ServletRequest进行替换,以便可重复读取请求体
        String body = ((RequestWrapper) webRequest.getNativeRequest ()).getBody ();        
        return "此处可根据需要对请求体的数据进行获取,返回值为对标注了@JsonRequestBody注释的方法参数的赋值";
    }
}

参数解析器注入:

import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;


@Configuration
public class ResolverConfiguration {
    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    @PostConstruct
    public void injectSelfMethodArgumentResolver() {
        List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<> ();
        argumentResolvers.add(new JsonArgumentResolver ());
        //新参数解析器列表添加原参数解析器列表
        argumentResolvers.addAll(adapter.getArgumentResolvers());
        //处理器适配器中添加新参数解析器列表
        handlerAdapter.setArgumentResolvers(argumentResolvers);
    }
}

Json前后端实战

前端使用Json类型的请求体

未完待续

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浅尝即止何来突破

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值