创建 GSON 对象错误

Creating GSON object error

我正在尝试在 Java Servlet class 中创建 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 对象后,方法 returns 没有执行任何打印语句或记录任何异常。

但下面的代码工作正常:

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");

    }
}

我做错了什么?我正在使用 google gson 库 v2.3.1

Gson是一个主流库。

您的问题似乎与您的服务器设置有关:您使用类路径中的 Gson 库编译您的 servlet(当您 运行 您的程序时它也在类路径中,可能来自 IDE ).

但是当你把你的 war 放到服务器(Gson 丢失的地方)时 doPost 在遇到 new Gson() 时终止。因此,请确保在编译时和 运行 时在类路径中都有 Gson 库 jar