简体   繁体   English

NullPointerException - 尝试从 Web 服务返回 JSON

[英]NullPointerException - Attempting to return JSON from Web Service

Please be patient as this is my first time learning about how to use web services.请耐心等待,因为这是我第一次学习如何使用 Web 服务。

I am trying to build a simple system that when given a parameter (String id), the web service returns a JSON object.我正在尝试构建一个简单的系统,当给定参数(字符串 id)时,Web 服务会返回一个 JSON 对象。 I am somewhat following this codebase as a guide https://o7planning.org/en/11207/simple-crud-example-with-java-restful-web-service我有点遵循这个代码库作为指南https://o7planning.org/en/11207/simple-crud-example-with-java-restful-web-service

Problem: When I run the service and go the URL http://localhost:8080/RESTfulServiceLIT_war_exploded/users/ {id}, I receive a NullPointer exception in the glassfish log.问题:当我运行服务并访问 URL http://localhost:8080/RESTfulServiceLIT_war_exploded/users/ {id} 时,我在 glassfish 日志中收到 NullPointer 异常。 It should simply display the JSON object relative to the user object returned from the id.它应该简单地显示相对于从 id 返回的用户对象的 JSON 对象。

Here is the UserDAO class code这是 UserDAO 类代码

import java.util.*;

public class UserDAO {
    private static final Map<String, User> userMap = new HashMap<String, User>();

    static {
        initUsers();
    }

    private static void initUsers() {
        User u1 = new User("K1", "Student 1", "Student");
        User u2 = new User("K2", "Student 2", "Student");
        User u3 = new User("K3", "Student 3", "Student");
        User u4 = new User("S1", "Staff 1", "Staff");
        User u5 = new User("S2", "Staff 2", "Staff");
        User u6 = new User("S3", "Staff 3", "Staff");

        userMap.put(u1.getId(), u1);
        userMap.put(u2.getId(), u2);
        userMap.put(u3.getId(), u3);
        userMap.put(u4.getId(), u4);
        userMap.put(u5.getId(), u5);
        userMap.put(u6.getId(), u6);
    }

    public static User getUser(String id) {
        return userMap.get(id);
    }


    public static List<User> getAllUsers() {
        Collection<User> c = userMap.values();
        List<User> list = new ArrayList<User>();
        list.addAll(c);
        return list;
    }

    List<User> list;

}

Here is the Main class that has the rest service这是具有其余服务的 Main 类

import javax.print.attribute.standard.Media;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;

// The Java class will be hosted at the URI path "/helloworld"
@Path("/users")

public class Main {

    @GET
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @Path("/{id}")
    public User getUser(@PathParam("id") String id) {
        return UserDAO.getUser(id);
    }

//    @GET
//    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
//    @Path{"/all"}
//    public List<User> getUsers_JSON(){
//        List<User> listOfUsers = UserDAO.getAllUsers();
//        return listOfUsers;
//    }


}

Here is the server log这是服务器日志

[2018-05-22T20:09:17.937+0100] [glassfish 4.1] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=35 _ThreadName=http-listener-1(3)] [timeMillis: 1527016157937] [levelValue: 900] [[
  StandardWrapperValve[MyApplication]: Servlet.service() for servlet MyApplication threw exception
java.lang.NullPointerException
    at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.writeTo(MOXyJsonProvider.java:944)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86)
    at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
    at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
    at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:683)
    at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:424)
    at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:414)
    at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:312)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:292)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1139)
    at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:460)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
    at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:748)
]]

User class用户类

public class User {

    private String id;
    private String name;
    private String type;

    User(){}

    User(String id, String name, String type){
        this.setId(id);
        this.setName(name);
        this.setType(type);
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

The URL:网址:

http://localhost:8080/RESTfulServiceLIT_war_exploded/users/{id}

is a path specification used by Jersey to state how you can access data.是 Jersey 用来说明如何访问数据的路径规范。 If you simply typed that string into your web browser, then you will get a NullPointerException .如果您只是在 Web 浏览器中键入该字符串,那么您将得到一个NullPointerException

What happens when you type:键入时会发生什么:

http://localhost:8080/RESTfulServiceLIT_war_exploded/users/K1

? ?

I resolved the same issue today.我今天解决了同样的问题。 Issue came when you called bean method in rest api.当您在 rest api 中调用 bean 方法时出现问题。

so create beans.xml file in WEB-INF folder所以在 WEB-INF 文件夹中创建 beans.xml 文件

include the following包括以下这些

 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd" bean-discovery-mode="all"> </beans>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM