我正在尝试在 Java Servlet 类中创建 Gson 对象。
public class SendNews extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Before creating");
Gson gsonObj = new Gson();
System.out.println("This line and the whole code below will be skipped.");
System.out.println("And this method will be finished without Exceptions.");
}
}
我尝试过使用
Gson gsonB = new GsonBuilder().create();
同样的问题。创建 Gson 对象后,该方法返回,但没有执行任何 prints 语句,也没有记录任何异常。
但是下面的代码可以正常工作:
public class Main {
public static void main(String[] args) {
//GcmSender.post(new NewsContent());
System.out.println("Before creating");
Gson gsonB = new Gson();
System.out.println("After creating");
}
}
我做错了什么?我正在使用谷歌 gson 库 v2.3.1
最佳答案
Gson 是一个主流库。
您的问题似乎与您的服务器设置有关:您在类路径中使用 Gson 库编译了 servlet(当您运行程序时,它也位于类路径中,可能是从 IDE 运行的)。
但是当您将 war 发送到服务器(缺少 Gson)时,doPost
会在遇到 new Gson()
时终止。因此,请确保在编译时和运行时的类路径中都有 Gson 库 jar。
关于java - 创建GSON对象错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30792490/