服务端获取的json字符串如下:{"name":"王五","course":{"chinese":70,"english":90}};
转化成student对象,代码如下:
package sourceCode;
import java.io.BufferedReader;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
public class TestJson extends HttpServlet{
public void doPost(HttpServletRequest res,HttpServletResponse req) throws IOException{
req.setHeader("Content-Type", "application/json;charset=utf-8");
BufferedReader br = res.getReader();
StringBuffer sb = new StringBuffer();
String str;
while((str=br.readLine())!=null){
sb.append(str);
}
String jsonStr = sb.toString();
System.out.println("sb为:"+jsonStr);
br.close();
Gson gson = new Gson();
Student stu = gson.fromJson(jsonStr, Student.class);
System.out.println(stu.getName);
System.out.println(stu.getCourse().getChinese());
}
}
student和sourse类代码如下:
public class Student {
private String name;
private Course course;
public Student() {
super();
}
public Student(String name, Course course) {
super();
this.name = name;
this.course = course;
}
//此处省略set和get函数
}
public class Course {
private int chinese;
private int english;
public Course() {
super();
}
public Course(int chinese, int english) {
super();
this.chinese = chinese;
this.english = english;
}
//此处省略set和get函数
}
当前台发起请求servlet时,控制台打印出的结果如下: