Джерси 2.x JAXB дает JSON, отличное от Джерси 1.x JAXB - PullRequest
0 голосов
/ 08 мая 2020

Мы переходим с jersey 1.x на 2.x и решили использовать Moxy JAXB.

Но столкнулись с проблемой преобразования json из POJO:

POJO:

@XmlRootElement(name = "result")
public class NotificationList {
    private PermissionInfo permissionInfo;
    private Collection<Notification> items;

    public NotificationList() {}

    public NotificationList(Collection<Notification> items) {
        this.items = items;
    }

    public PermissionInfo getPermissionInfo() {
        return permissionInfo;
    }

    public void setPermissionInfo(PermissionInfo permissionInfo) {
        this.permissionInfo = permissionInfo;
    }

    @XmlElementWrapper(name = "notifications")
    @XmlElement(name = "notification")
    public Collection<Notification> getItems() {
        return items;
    }
}

для вышеуказанного json вывода с jersey 1.x - Jackson JAXB Старый JSON формат

{
    "notifications": [
        {
            "notification": [
                {
                     "id" : 1,
                     "name" : "name1"
                },
                {
                     "id" : 2,
                     "name" : "name2"
                }
              ]
        }
    ],
    "name": "list"
}

Но теперь с jersey 2.x и Moxy получил вывод как:

{
   "notifications" : {
      "notification" : [ {
         "id" : 1,
         "name" : "name1"
      }, {
         "id" : 2,
         "name" : "name2"
      } ]
   },
   "name" : "list"
}

и попробовал установить JSON_WRAPPER_AS_ARRAY_NAME = "eclipselink. json .wrapper-as-array-name" свойство как true и он дает вывод как:

{
   "notifications" : [ {
      "id" : 1,
      "name" : "name1"
   }, {
      "id" : 2,
      "name" : "name2"
   } ],
   "name" : "list"
}

Пожалуйста, помогите мне, как достичь старого JSON формата , и спасибо за помощь.

в Джерси 1 .x создание JAXBContext, например:

new JSONJAXBContext(JSONConfiguration.natural().build(), classesToBeBound)

в jersey 2.x, например:

@Provider
public class MoxyJsonContextResolver implements ContextResolver<MoxyJsonConfig> {

    private final MoxyJsonConfig config;

    public MoxyJsonContextResolver() {
        config = new MoxyJsonConfig().
                setFormattedOutput(true)
                .property(JAXBContextProperties.JSON_WRAPPER_AS_ARRAY_NAME, true)
                .property(JAXBContextProperties.JSON_TYPE_COMPATIBILITY, true);
    }

    @Override
    public MoxyJsonConfig getContext(Class<?> type) {
        return config;
    }

}

Jackson2 не используется из-за https://github.com/FasterXML/jackson-modules-base/issues/47 открытая проблема

...