1.Json传递数据两种方式(json大全)
----------------------------字符串
       var list1 = ["number","name"];
var param = {};
param["list1"] = list1;
param["test"] ="java";
var json = JSON.stringify(param);
$.ajax({
type: 'POST',
url: CTX + '双击查看原图eckInvoice双击查看原图st',
data: {
ids: json
},
dataType: "json",
async:false,
success: function(data){
if(data.success) {
value = 'success';
$("#table").bootstrapTable('refresh');
} else {
value = 'fail';
}
showAlertFrame(value, data.message);
},
error: function (e) {
}
});
};
    @PostMapping(value = "/list")
@ResponseBody
public void invoiceDetail2(String ids) {
JSONObject jsonobject = JSONObject.parseObject(ids);
JSONArray jsonArray = JSONArray.parseArray(jsonobject.get("list1").toString());
List<String> list = jsonArray.toJavaList(String.class);
} @PostMapping(value = "/list2")
@ResponseBody
public void list2(@RequestBody ScannerVo vo) {
List<String> list = vo.getList1();
// JSONArray jsonArray = JSONArray.parseArray(vo.getList1());
// List<String> list = jsonArray.toJavaList(String.class);
}

-------------------------------------对象



public class ScannerVo {

    private List list1;

    public List getList1() {
return list1;
} public void setList1(List list1) {
this.list1 = list1;
} public String getTest() {
return test;
} public void setTest(String test) {
this.test = test;
} private String test; }
var getInvoice = function (invoiceCode,invoiceNum) {
var list1 = ["number","name"];
var param = {};
param["list1"] = list1;
param["test"] ="java";
var json = JSON.stringify(param);
$.ajax({
type: 'POST',
url: CTX + '/checkInvoice/list2',
data: json,
dataType: "json",
async:false,
contentType: 'application/json',
success: function(data){
if(data.success) {
value = 'success';
$("#table").bootstrapTable('refresh');
} else {
value = 'fail';
}
showAlertFrame(value, data.message);
},
error: function (e) { }
}); };
    @PostMapping(value = "双击查看原图st2")
@ResponseBody
public void list2(@RequestBody ScannerVo vo) {
List<String> list = vo.getList1();
// JSONArray jsonArray = JSONArray.parseArray(vo.getList1());
// List<String> list = jsonArray.toJavaList(String.class);
}




springmvc接收json数据的4种方式

ajax我经常用到,传的数据是json数据,json数据又有对象,数组。所有总结下springmvc获取前端传来的json数据方式:

1、以RequestParam接收

前端传来的是json数据不多时:[id:id],可以直接用@RequestParam来获取值

@Autowired
private AccomodationService accomodationService; @RequestMapping(value = "/update")
@ResponseBody
public String updateAttr(@RequestParam ("id") int id) {
int res=accomodationService.deleteData(id);
return "success";
}

2、以实体类方式接收

前端传来的是一个json对象时:{【id,name】},可以用实体类直接进行自动绑定

@Autowired
private AccomodationService accomodationService; @RequestMapping(value = "/add")
@ResponseBody
public String addObj(@RequestBody Accomodation accomodation) {
this.accomodationService.insert(accomodation);
return "success";
}

3、以Map接收

前端传来的是一个json对象时:{【id,name】},可以用Map来获取

@Autowired
private AccomodationService accomodationService; @RequestMapping(value = "/update")
@ResponseBody
public String updateAttr(@RequestBody Map<String, String> map) {
if(map.containsKey("id"){
Integer id = Integer.parseInt(map.get("id"));
}
if(map.containsKey("name"){
String objname = map.get("name").toString();
}
// 操作 ...
return "success";
}

4、以List接收

当前端传来这样一个json数组:[{id,name},{id,name},{id,name},...]时,用List<E>接收

@Autowired
private AccomodationService accomodationService; @RequestMapping(value = "/update")
@ResponseBody
public String updateAttr(@RequestBody List<Accomodation> list) {
for(Accomodation accomodation:list){
System.out.println(accomodation.toString());
}
return "success";
}




Springmvc接受json参数总结

关于springmvc的参数我觉得是个头痛的问题,特别是在测试的时候,必须要正确的注解和正确的contype-type 后端才能被正确的请求到,否则可能报出400,415等等bad request。
1,最简单的GET方法,参数在url里面,比如:
@RequestMapping(value = “/artists/{artistId}”, method = {RequestMethod.GET})
@PathVariable去得到url中的参数。
public Artist getArtistById(@PathVariable String artistId)
2,GET方法,参数接在url后面。

@RequestMapping(value = "/artists", method = {RequestMethod.GET})
public ResponseVO getAllArtistName(
@RequestParam(name = "tagId", required = false) final String tagId)

访问的时候/artists?tagId=1
@RequestParam相当于request.getParameter(“”)

3,POST方法,后端想得到一个自动注入的对象

@RequestMapping(value = "/addUser", method = {RequestMethod.POST})
public void addUser(@RequestBody UserPO users){

这里要注意@RequestBody,它是用来处理前台定义发来的数据Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;我们使用@RequestBody注解的时候,前台的Content-Type必须要改为application/json,如果没有更改,前台会报错415(Unsupported Media Type)。后台日志就会报错Content type ‘application/x-www-form-urlencoded;charset=UTF-8’ not supported
如果是表单提交 Contenttype 会是application/x-www-form-urlencoded,可以去掉@RequestBody注解
---------------------

这时聪明的spring会帮我按照变量的名字自动注入,但是这是很容易遇到status=400
 
<html><body><h1>Whitelabel Error Page</h1><p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p><div id='created'>Tue Feb 06 16:49:34 GMT+08:00 2018</div><div>There was an unexpected error (type=Bad Request, status=400).</div><div>Validation failed for object='user'. Error count: 1</div></body></html>1
这是springboot的报错,原因是bean中有不能注入的变量,因为类型的不一样,一般是date和int的变量,所以在使用的时候要特别注意。
---------------------

如果前端使用的$.ajax来发请求,希望注入一个bean。这时又有坑了,代码如下:

$.ajax({
headers: {
Accept: "application/json; charset=utf-8"
},
method : 'POST',
url: "http://localhost:8081/user/saveUser",
contentType: 'application/json',
dataType:"json",
data: json,
//async: false, //true:异步,false:同步
//contentType: false,
//processData: false,
success: function (data) {
if(data.code == "000000"){
alert(data.desc);
window.location.href="http://localhost:8081/login.html";
}
},
error: function (err) {
alert("error"); }});
---------------------

马上就报错了:
**error
:
“Bad Request”
exception
:
“org.springframework.http.converter.HttpMessageNotReadableException”
message
:
“JSON parse error: Unrecognized token ‘name’: was expecting ‘null’, ‘true’, ‘false’ or NaN; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token ‘name’: was expecting ‘null’, ‘true’, ‘false’ or NaN↵ at [Source: java.io.PushbackInputStream@7fc056ba; line: 1, column: 6]”
path
:
“/user/saveUser”
status
:
400
timestamp
:
1518094430114**
这是看看发送的参数:

居然不是我拼装好的json,
data: json,  改成 data: JSON.stringify(json),后端接收json String,json只是个对象,所以解析不了!
---------------------

4,POST方法,需要得到一个List的类型
@RequestMapping(value = “/addUser”, method = {RequestMethod.POST})
    public void addUser(@RequestBody List users){
---------------------

5,POST方法,后台需要得到一个List类型。

@RequestMapping(value = "/getPlayURL", method = {RequestMethod.POST})
@ResponseBody
public List<Song> getPlayUrlBySongIds(
@RequestParam(name = "songId",required = false) List<String> songIdList) {
---------------------







004-SpringMVC-如何接收各种参数(普通参数,对象,JSON, URL)

在交互的过程中,其中一个关键的节点就是获取到客户端发送过来的请求参数,本篇文章,我们来罗列下SpringMVC对于各种数据的获取方式:说明:以下重点在讲解如何获取参数上,所以返回的数据不是重点1,普通方式,请求参数名跟Controller的方法参数一致1.1 创建Controller
--------------------- 

1.2 发送请求做测试(由于方法没有限制请求方式,所以get和post均可)

2,当请求参数过多时,以对象的方式传递

2.1 创建一个类,包含多个参数(简单不附带图了)

2.2 前台传递参数的方式不变

2.3 后台接收参数的方法

原因很简单,是因为SpringMVC默认是没有对象转换成json的转换器,所以需要手动添加jackson依赖。<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.8.8</version></dependency>
---------------------

3,当请求参数名跟方法参数名不一致时,@RequestParam

4,当需要传递Json格式的数据是,@RequestBody

4.1 前台传递的方式是json

5,通过URL的方式传递参数

Json传递数据两种方式(json大全)的更多相关文章

  1. spring接收json字符串的两种方式

    一.前言 前几天遇到一个问题,前端H5调用我的springboot一个接口(post方式,@RequestParameter接收参数),传入的参数接收不到.自己测试接口时使用postman的form- ...

  2. Asp.net Web API 返回Json对象的两种方式

    这两种方式都是以HttpResponseMessage的形式返回, 方式一:以字符串的形式 var content = new StringContent("{\"FileName ...

  3. java后台处理解析json字符串的两种方式

    简单说一下背景 上次后端通过模拟http请求百度地图接口,得到的是一个json字符串,而我只需要其中的某个key对应的value. 当时我是通过截取字符串取的,后来觉得不太合理,今天整理出了两种处理解 ...

  4. [转]Angular2-组件间数据传递的两种方式

    本文转自:https://www.cnblogs.com/longhx/p/6960288.html Angular2组件间数据传递有多种方式,其中最常用的有两种,一种是配置元数据(或者标签装饰),一 ...

  5. Angular2-组件间数据传递的两种方式

    Angular2组件间数据传递有多种方式,其中最常用的有两种,一种是配置元数据(或者标签装饰),一种是用单例模块传递:有两个元数据具有传递数据的功能:inputs和outputs. 一.元数据传递 1 ...

  6. Java - 格式化输出JSON字符串的两种方式

    目录 1 使用阿里的fastjson 1.1 项目的pom.xml依赖 1.2 Java示例代码 2 使用谷歌的gson 2.1 项目的pom.xml依赖 2.2 Java示例代码 1 使用阿里的fa ...

  7. Gson解析复杂JSON字符串的两种方式

    JSON解析可以使用的库: JSONObject(源自Android官方). Gson(源自Google). Jackson(第三方开源库). FastJSON(第三方开源库). 本文例子使用Goog ...

  8. json 序列化的两种方式

    JavaScriptSerializer Serializer = new JavaScriptSerializer(); ResultData<EUserData> resultMode ...

  9. Unity 读取Json常用的两种方式

    使用的是Litjson 1.读取本地Json public void ReadJson() { StreamReader streamReader = new StreamReader(Applica ...

随机推荐

  1. Linux之 nginx-redis-virtualenv-mysql

    mysql maraidb相关 .yum安装好,启动 安装: yum install mariadb-server mariadb 启动mabiadb: systemctl start mariadb ...

  2. Vue-cli 搭建web服务介绍

    Node.js 之 npm 包管理 - Node.js 官网地址:点我前往官网 - Node.js 中文镜像官网: 点我前往```` Node.js 是一个基于 Chrome V8 引擎的 JavaS ...

  3. python与用户交互、数据类型

    一.与用户交互 1.什么是用户交互: 程序等待用户输入一些数据,程序执行完毕反馈信息. 2.如何使用 在python3中使用input,input会将用户输入的如何内容存为字符串:在python中分为 ...

  4. LuoGu P1004 方格取数

    题目传送门 一开始这个题我是不会的(沙华弱DP啊QwQ),后来考完试我一想,这东西怎么和数字三角形那题这么像啊? 都是自上而下,只能向下或者向右,求一个max 那么...这不就是个走两遍的数字矩阵嘛 ...

  5. 高级UI特效—用SVG码造一个精美的中国地图

    前言 来继续学习SVG,要想深入了解还是要多动手进行实战.关于svg基础可以去看一下我的上一篇文章<SVG前戏—让你的View多姿多彩>,今天就用SVG打造一个精美的UI效果. 正文 先上 ...

  6. vuforia unity 识别图片出模型

    ARCamera设置: 然后设置ImageTarge

  7. LeetCode(1): 两数之和

    本内容为LeetCode第一道题目:两数之和 # -*- coding: utf-8 -*- """ Created on Sun Mar 10 19:57:18 201 ...

  8. centos7安装laravel

    一. 安装前准备1. 安装screenyum install screen 2. 安装wgetyum install wget 3. 更新yumyum update 4. 安装额外资源库yum ins ...

  9. Linux之man命令详解及中文汉化

    使用方法 Linux man中的man就是manual的缩写,用来查看系统中自带的各种参考手册 使用方法: man command 示例: [root@VM_0_13_centos ~]# man l ...

  10. Centos6.8部署jumpserver(完整版)

    环境: 系统 Centos6.8 IP:192.168.66.131 关闭selinux和防火墙 # 修改字符集,否则可能报 input/output error的问题,因为日志里打印了中文 # lo ...