Не найден сериализатор для класса ... (во избежание исключения отключите SerializationFeature.FAIL_ON_EMPTY_BEANS) - PullRequest
0 голосов
/ 16 мая 2019

Цель: создать API, который позволит мне искать данные в журнале статей, получать их данные в классе Item, отображать их в формате Json. Путь: я создал проект на Liferay 6.1 с помощью плагина портлета Service Builder. В моем файле service.xml я создал сущность Item. Поля в этой сущности обновляются восстановленными данными журнала статей. Эти данные затем отображаются в формате JSON.

Возникли проблемы: я могу отображать данные в JSON на консоли Eclipse с _log.info (Item). Поэтому я получаю их обратно, но не могу опубликовать их через Почтальон.

Он показывает мне эту ошибку: No serializer found for class java.util.Collections$3 and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.beorn.tm.synchro.model.impl.ItemImpl["expandoBridge"]->$Proxy760["attributeNames"])

Мои разные классы:

public class SynchroApplication extends ResourceConfig {

    public SynchroApplication() {
        //packages("com.beorn.tm.api");
        register(BanqueRestService.class);
        register(HelloWS.class);
        register(JournalArticleRestService.class);

        register(JacksonFeature.class);

        //Register Auth filter 
        register(AuthenticationFilter.class);
    }

       public static ObjectMapper getObjectMapper() {

           ObjectMapper mapper = new ObjectMapper();

           mapper.configure(com.fasterxml.jackson.databind.SerializationFeature.
                    WRITE_DATES_AS_TIMESTAMPS, true);

            mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
                    .withFieldVisibility(JsonAutoDetect.Visibility.NONE)
                    .withGetterVisibility(JsonAutoDetect.Visibility.ANY)
                    .withSetterVisibility(JsonAutoDetect.Visibility.ANY)
                    .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

            mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

            mapper.enable(SerializationFeature.INDENT_OUTPUT);

            mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

            return mapper;
        }

        public static String toJson(Object c) throws JsonProcessingException {
            ObjectMapper mapper = getObjectMapper();
            return mapper.writeValueAsString(c);
        }

        public static JsonNode fromJson(String input) throws Exception {
            ObjectMapper mapper = getObjectMapper();
            return mapper.readTree(input);
        }
}
@Path("synchro")
public class JournalArticleRestService {

    private static final Log _log = LogFactoryUtil.getLog(JournalArticleRestService.class);

    @GET
    @Path("/date")
    @Produces(MediaType.APPLICATION_JSON)
    public Item getJournalArticleAfter01012019() {

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Locale locale = Locale.FRANCE;

        ItemImpl item = new ItemImpl();


        try {
            Date date01012019 = sdf.parse("01/01/2019");
            //Companies
            List<Company> companies = CompanyLocalServiceUtil.getCompanies();
            for(Company company : companies) {
                long companyId = company.getCompanyId();
                //Groups
                List<Group> groups = GroupLocalServiceUtil.getCompanyGroups(companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
                for(Group group : groups) {
                    long groupId = group.getGroupId();
                    //Articles
                    List<JournalArticle> articles = JournalArticleLocalServiceUtil.getArticles(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
                    for(JournalArticle article: articles) {
                        if(article.getModifiedDate().after(date01012019))  {
                            _log.info(article.getCreateDate() + " : " + article.getStructureId());

                            long articleGroupId = article.getGroupId();
                            long articleCompanyId = article.getCompanyId();
                            long userId = article.getUserId();
                            String userName = article.getUserName();
                            Date createDate = article.getCreateDate();
                            Date modifiedDate = article.getModifiedDate();
                            String className = article.getClassName();
                            long classPK = article.getClassPK();
                            int status = article.getStatus();
                            Date statusDate = article.getStatusDate();

                            item.setGroupId(articleGroupId);
                            item.setCompanyId(articleCompanyId);
                            item.setUserId(userId);
                            item.setUserName(userName);
                            item.setCreateDate(createDate);
                            item.setModifiedDate(modifiedDate);
                            item.setClassname_(className);
                            item.setClassPK(classPK);
                            item.setStatus(status);
                            item.setStatusDate(statusDate);
                            _log.info(item);

                        }
                    }
                }
            }

        } catch (SystemException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return item;

    }

}
<service-builder package-path="com.beorn.tm.synchro">

    <namespace>synchronizationAPI</namespace>

    <entity name="Item" uuid="true" local-service="true" remote-service="false">

        <!-- PK fields -->
        <column name="itemId" type="long" primary="true" />

        <!-- Group instance -->
        <column name="groupId" type="long" />

        <!-- Audit fields -->
        <column name="companyId" type="long" />
        <column name="userId" type="long" />
        <column name="userName" type="String" />
        <column name="createDate" type="Date" />
        <column name="modifiedDate" type="Date" />

        <!-- Other fields -->
        <column name="classname_" type="String" db-name="classname" />
        <column name="classPK" type="long" />
        <column name="status" type="int" />
        <column name="statusMessage" type="String" />
        <column name="statusDate" type="Date" />

        <!-- Order -->
        <order by="asc">
            <order-column name="createDate" />
        </order>

        <!-- Finder methods -->
        <finder name="CompanyId" return-type="Collection">
            <finder-column name="companyId" />
        </finder>
        <finder name="GroupId" return-type="Collection">
            <finder-column name="groupId" />
        </finder>
        <finder name="GroupIdAndClassName" return-type="Collection">
            <finder-column name="groupId" />
            <finder-column name="classname_" />
        </finder>
        <finder name="GroupIdAndClassNameAndStatus" return-type="Collection">
            <finder-column name="groupId" />
            <finder-column name="classname_" />
            <finder-column name="status" />
        </finder>

    </entity>

    <exceptions>
        <exception>StatusNotFound</exception>
    </exceptions>

</service-builder>

Спасибо за ваши ответы

...