服务端获取的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时,控制台打印出的结果如下:
亲测,直接使用是没问题的,那就应该是两次提交,第二次字符串为空
这是前端造成的,请求应该是提了两次造成。
Gson gson = new Gson();
在这句前面你应该先判断是否为空,空了自然无法处理。
if("".equals(jsonStr)) return;
前端问题,前端发了两次请求,第二次发过来的数据为空。你的后台要处理一下,如果jsonStr 为空或者是“”,就不要处理