java中json的 *** 作
servlet代码:
package com.zx.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zx.entity.Clas;
import com.zx.entity.Student;
import com.zx.entity.Teacher;
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("LoginServlet---doGet");
Gson gson = new Gson();
//1、java对象转json字符串
Teacher[] teas = new Teacher[] {new Teacher(11, "张老师"), new Teacher(12, "李老师")};
Clas clas = new Clas(101, "一年一班");
Clas clas1 = new Clas(102, "一年二班");
Student stu = new Student(10, "张三", clas, teas);
String json_str1 = gson.toJson(stu);
System.out.println("json字符串1:"+json_str1);
//1.1、json字符串转java对象
// gson.fromJson(json_str1, new MyTypeToken().getType());
//protected,匿名内部类
Student stu1 = gson.fromJson(json_str1, new TypeToken() {}.getType());
System.out.println("stu1:"+stu1);
//2、java对象list集合和json的转换
List list = new ArrayList<>();
list.add(clas);
list.add(clas1);
String json_str2 = gson.toJson(list);
System.out.println("json字符串2:"+json_str2);
//2.1、json字符串转集合
List list1 = gson.fromJson(json_str2, new TypeToken>() {}.getType());
System.out.println("list1:"+list1.get(1).toString());
//3、map 对象和json 的转换
Map map = new HashMap<>();
map.put("one", clas);
map.put("two", clas1);
String json_str3 = gson.toJson(map);
System.out.println("json字符串3:"+json_str3);
//3.1、json字符串转map
Map map1 = gson.fromJson(json_str3, new TypeToken
前端页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
登录
web.xml代码
javaweb13
loginServlet
com.zx.servlet.LoginServlet
loginServlet
/login
需要jar包:
gson-2.2.4.jar
访问路径:
localhost:8080/javaweb13/login
评论列表(0条)