POST-запрос к клиенту Джерси не может демонтировать JSON-объект, который содержит пустой массив? - PullRequest
1 голос
/ 21 мая 2019

Я использую сервер джерси, который при получении запроса POST curl -X POST \ http://localhost:8080/ca/accountSettings \ -H 'Content-Type: application/json' \ -d '{ "socialAccountTypeId":"adqasocialaccount", "imgUrl":"https://test.com/logo.png", "descriptionDefault":"TEST Account", "descriptionLangId":"EN", "nameDefault":"Social Account", "nameLangId":"en", "types":["test"], "credentialsType":"OAUTH_20", "marketAssociation":[] }' поле marketAssociation выводится как "marketAssociation: [" "], а не как пустой массив, как ожидалось. Все остальное корректно выводится.

Я попытался инициализировать массив marketAssociation в классе пустым массивом, но безуспешно.

API Route

@POST
    @Path("/ca/accountSettings")
    public Response addAccountSettings(SocialAccountType socialAccountType)
    {
        String endpoint = "POST /ca/accountSettings";
        Response response = null;
        try
        {
            WCResponse wcResponse = this.sssApi.addSocialAccountType(socialAccountType);
catch (Exception e)
        {
            TestApi.log.error("Exception in " + endpoint, e.getMessage());
            response = response.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }

Класс SocialAccountType

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SocialAccountType", propOrder = {
    "socialAccountTypeId",
    "imgUrl",
    "descriptionDefault",
    "descriptionLangId",
    "nameDefault",
    "nameLangId",
    "types",
    "credentialsType",
    "marketAssociation",
    "creationTime"
})
@XmlRootElement(name = "SocialAccountType")
public class SocialAccountType {

    @XmlElement(required = true)
    protected String socialAccountTypeId;
    @XmlElement(required = true)
    protected String imgUrl;
    @XmlElement(required = true)
    protected String descriptionDefault;
    @XmlElement(required = true)
    protected String descriptionLangId;
    @XmlElement(required = true)
    protected String nameDefault;
    @XmlElement(required = true)
    protected String nameLangId;
    protected List<String> types;
    @XmlElement(required = true)
    protected CredentialsType credentialsType;
    protected List<String> marketAssociation;
    protected String creationTime;
}

Для класса существуют методы получения и установки, но они являются общими, и я не думаю, что они актуальны.

Я ожидаю, что marketAssociation просто должен быть пустым массивом marketAssociation: [], а не marketAssociation: [""]

Это пользовательский преобразователь контекста JAXB, который я использую

@Provider
@Singleton
public class JAXBContextResolver implements ContextResolver<JAXBContext>
{

    private JAXBContext context;
    @SuppressWarnings("rawtypes")
    private Class[] types = { Device.class, EndUser.class, SocialAccountType.class, SocialAccountTypeList.class };

    public JAXBContextResolver() throws Exception
    {
        this.context = new JSONJAXBContext(JSONConfiguration
                                                   .mapped()
                                                   .arrays("userList", "deviceList", "roles", "socialAccountType", "marketAssociation", "types")
                                                   .build(), types);
    }

    @Override
    @SuppressWarnings("rawtypes")
    public JAXBContext getContext(Class<?> objectType)
    {
        for (Class c : types)
        {
            if (c.equals(objectType))
                return (context);
        }
        return (null);
    }
}

1 Ответ

0 голосов
/ 21 мая 2019

Какой процессор JSON вы используете? Из того, что я понял, дефолт (JAXB) делает некоторые странности с пустыми массивами, и переключение на Джексона часто исправляет такие проблемы. Смотрите третий ответ здесь:

Невозможно разархивировать массив объектов JSON с помощью клиента Jersey

...