【问题标题】:restful web service response with json带有 json 的宁静 Web 服务响应
【发布时间】:2016-12-17 21:31:02
【问题描述】:

我有一个返回用户列表的宁静网络服务,我想以 json 格式做出响应,但会产生以下异常:

    SEVERE: Servlet.service() for servlet [RESTful] in context with path [/spring] threw exception
org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )

我的宁静方法:

@GET
 @Path("all")
 @Produces(MediaType.APPLICATION_JSON)
 public Response getUsers(){
     UserService service = new UserService();
     List<UserBean> userBeans = service.getUsers();
     JSONObject users = new JSONObject();

     if(userBeans != null)
     {
         for(UserBean user : userBeans)
         {
             users.put("name",user.getUsername());
         }

         System.out.println(users);
         return Response.status(200).entity(users).build(); 
     }
     return Response.status(201).entity("faild").build();   
   }

【问题讨论】:

  • 你在用 Jersey 吗?
  • 是的,我用过,有什么问题吗??

标签: json rest jersey


【解决方案1】:

要使用 Jersey 生成 JSON,您不需要使用 org.json.JSONObject 类。

确保您已配置 JSON 提供程序(有关详细信息,请参阅 this answer)并将您的资源方法更改为如下:

@GET
@Path("all")
@Produces(MediaType.APPLICATION_JSON)
public Response getUsers() {

    UserService service = new UserService();
    List<UserBean> users = service.getUsers();

    return Response.ok(users).build();
}

【讨论】:

    猜你喜欢
    • 2018-04-21
    • 1970-01-01
    • 2013-07-29
    • 2015-07-19
    • 2019-04-15
    • 2019-03-17
    • 1970-01-01
    • 2013-12-07
    • 2021-05-24
    相关资源
    最近更新 更多