gson

地址 https://search.maven.org/artifact/com.google.code.gson/gson/2.8.5/jar
github https://github.com/google/gson
引入maven

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.5</version>
    </dependency>

文档

http://www.javadoc.io/doc/com.google.code.gson/gson/2.8.5

栗子

json转化为java的类即进行序列化 反序列化 http://static.javadoc.io/com.google.code.gson/gson/2.8.5/com/google/gson/package-summary.html

代码如下

package com.ming.servlet;

import com.google.gson.Gson;
import com.ming.vo.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class CheckServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 初始化序列化工具
        Gson gson = new Gson();
        // 反序列化
        BufferedReader reader = req.getReader();
        User getUser = gson.fromJson(reader, User.class);
        // 序列化
        User user = new User();
        user.setId(22);
        user.setUserName("ming");
        user.setPassword("ming");
        // 转json
        String json = gson.toJson(user);
        // 进行回应
        resp.setContentType("application/json");
        PrintWriter out = resp.getWriter();
        out.println(json);
        out.close();
    }
}

ps 实际上更加复杂,涉及到字符串的转化,流的问题,即 字节流转String request获取body使用getInputStream即获得到字节流,再次新建StringBuffer 每次使用read读取值,放入byte中,然后再次新建String,放入StringBuffer 这样完成了流转化string,继续需要考虑,其内部是使用了反射机制,通过反射,生成对象.
还需要考虑,当json过大的时候,出现内存溢出问题. 挺复杂的...