JSON - 无法使用Jackson和JPA在Object中序列化JSONObject

时间:2018-04-28 06:52:58

标签: java serialization jackson

我有一个MovieService和SerieService。 MovieService返回一组电影,SerieService收集一系列电影。

看来错误,我不明白其含义。我只想返回并显示搜索的响应。

"No serializer found for class org.udg.pds.simpleapp_javaee.rest.SearchRESTService$SearchResult and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)"

这是我的代码:

package org.udg.pds.simpleapp_javaee.rest;

@Path("/search")
@RequestScoped
public class SearchRESTService extends RESTService {

@EJB
MovieService ms;

@EJB
SeriaService ss;

@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response search(@Context HttpServletRequest req) {
    if (!checkLoggedIn(req)) {
        throw new WebApplicationException("User not logged.");
    }

    SearchResult sr = new SearchResult();
    sr.movies = ms.getAllMovies();
    sr.series = ss.getAllSeries();
    return buildResponse(sr);
}


static class SearchResult {
    Collection<Movie> movies;
    Collection<Seria> series;
}
}

2 个答案:

答案 0 :(得分:0)

您需要将Jackson注释@JsonProperty添加到SearchResult的字段中,或者为这些字段提供getter实现。

来自文档:

  

默认的Jackson属性检测规则会找到:

     
      
  • 所有&#39;公共&#39;&#39;字段
  •   
  • 所有&#39;公共&#39;&#39; getter(&#39; getXxx()&#39;方法)
  •   

答案 1 :(得分:0)

如果你的字段没有getter / setter,你可以使用这个注释让Jackson找到它们

@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE)
static class SearchResult {

或者您可以在全局范围内执行此操作,配置映射器

ObjectMapper youMapper= new ObjectMapper();
youMapper.setVisibilityChecker(youMapper.getSerializationConfig().getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));