json转java
步骤:
1.导入jackson相关jar包
2.创建Jackson核心对象 ObjectMapper
3.调用ObjectMapper的相关方法进行转换
1.readValue( json字符串数据,Class )
//json转java @Test public void test5() throws Exception { //1.初始化JSON字符串 String json = "{\"gender\":\"男\",\"name\":\"张三\",\"age\":\"20\"}"; //2.创建一个ObjectMapper对象 ObjectMapper mapper = new ObjectMapper(); //3.转换为java对象 Person对象 Person person = mapper.readValue(json, Person.class); System.out.println(person);// Person{name='张三', age=20, gender='男', birthday=null} }
案例-校验用户名是否存在
服务器响应的数据,在客户端使用时,要想当做json数据格式使用
1.$.get ( type ):将最后一个参数type指定为" json "
2.在服务器设置MIME类型
resp.setContentType("application/json;charset=utf-8");
案例实现:
regist.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册页面</title> <script src="js/jquery-3.3.1.min.js"></script> <script> $(function () { //给username绑定blur事件 $("#username").blur(function () { //获取username文本输入框的值 let username = $(this).val(); //发送ajax请求 //期望服务器响应回的数据格式:{"userExsit":true,"msg":此用户太受欢迎,请更换一个} // {"userExsit":false,"msg":用户名可用} $.get("findUserServlet", {username: username}, function (data) { //判断userExsit键的值是否是true let span = $("s_username"); if (data.userExsit) { //用户名存在 span.css("color","red") span.html(data.msg); } else { //用户名不存在 span.css("color","green") span.html(data.msg); } },"json");// 响应格式 }); }); </script> </head> <body> <input type="text" id="username" name="username" placeholder="请输入用户名"> <span id="s_username"></span> <br> <input type="password" name="password" placeholder="请输入密码"> <br> <input type="submit" value="注册"> </body> </html>
FindUserServlet:
package com.example.servlet; import com.fasterxml.jackson.databind.ObjectMapper; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; import java.util.HashMap; @WebServlet(name = "findUserServlet", value = "/findUserServlet") public class FindUserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.获取用户名 String username = req.getParameter("username"); //2.调用service层判断用户名是否存在 //期望服务器响应回的数据格式:{"userExsit":true,"msg":此用户太受欢迎,请更换一个} // {"userExsit":false,"msg":用户名可用} //设置编码 // resp.setContentType("text/html;charset=utf-8"); resp.setContentType("application/json;charset=utf-8"); HashMap<String, Object> map = new HashMap<>(); if ("tom".equals(username)){ //存在 map.put("userExsit",true); map.put("msg","此用户太受欢迎,请更换一个"); }else { //不存在 map.put("userExsit",false); map.put("msg","用户名可用"); } //将map转为json,并且传递给客户端 //将map转为json ObjectMapper mapper = new ObjectMapper(); //并且传递给客户端 mapper.writeValue(resp.getWriter(), map); } }
标签:username,map,用户名,java,校验,json,msg,ObjectMapper From: https://www.cnblogs.com/qihaokuan/p/17105659.html