Как мне сериализовать JAXBElement?

Я использую:

  • GSON 2.3.1
  • апач-CXF-3.1.1
  • JBoss EAP 6.4

Я использую wsdl2java для создания клиента веб-сервиса из wsdl.

Я генерирую классы с:

@XmlElementRef(name = "FMLA_Code", namespace = "http://www.ultipro.com/contracts", type = JAXBElement.class)
protected JAXBElement<String> fmlaCode;

Когда я возвращаю объект из вызова веб-службы, я хочу сделать JSON-ответ вызывающей стороне.

EmploymentInformationGetResponse response =             port.getEmploymentInformationByEmployeeIdentifier(employeeNumberIdentifier);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeHierarchyAdapter(EmploymentInformationGetResponse.class, new EmploymentInformationGetResponseAdapter());
Gson gson = gsonBuilder.disableHtmlEscaping().create();
String s = gson.toJson(response);
System.out.println(s);

Результат содержит

fmlaCode=javax.xml.bind.JAXBElement@3191394e

Каков наилучший для меня способ получить значение?

Я могу, но предпочел бы не изменять сгенерированные классы, поскольку их, возможно, потребуется сгенерировать позже.

Я пытался создать адаптер типа для JAXBElement, но не вызывается:

public class JAXBElementAdapter extends TypeAdapter<JAXBElement> {

    @Override
    public void write(JsonWriter jsonWriter, JAXBElement jaxbElement) throws IOException {
        if (jaxbElement == null) {
            jsonWriter.nullValue();
            return;
        }
        JAXBElement e = jaxbElement;
        jsonWriter.value(e.getValue() != null ? e.getValue().toString() : "");
    }

    @Override
    public JAXBElement read(JsonReader jsonReader) throws IOException {
        return null;
    }
}

Я использовал этот код для регистрации адаптера:

    gsonBuilder.registerTypeHierarchyAdapter(JAXBElement.class, new JAXBElementAdapter());

Вот сгенерированный EmploymentInformationGetResponse

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlType;
import java.util.List;

/**
 * <p>Java class for EmploymentInformationGetResponse complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType name="EmploymentInformationGetResponse"&gt;
 *   &lt;complexContent&gt;
 *     &lt;extension base="{http://www.ultipro.com/contracts}GetResponse"&gt;
 *       &lt;sequence&gt;
 *         &lt;element name="Results" type="{http://www.ultipro.com/contracts}ArrayOfEmploymentInformation" minOccurs="0"/&gt;
 *       &lt;/sequence&gt;
 *     &lt;/extension&gt;
 *   &lt;/complexContent&gt;
 * &lt;/complexType&gt;
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "EmploymentInformationGetResponse", propOrder = {
    "results"
})
public class EmploymentInformationGetResponse
    extends GetResponse
{

    @XmlElementRef(name = "Results", namespace = "http://www.ultipro.com/contracts", type = JAXBElement.class)
    protected JAXBElement<ArrayOfEmploymentInformation> results;

    /**
     * Gets the value of the results property.
     * 
     * @return
     *     possible object is
     *     {@link JAXBElement }{@code <}{@link ArrayOfEmploymentInformation }{@code >}
     *     
     */
    public JAXBElement<ArrayOfEmploymentInformation> getResults() {
        return results;
    }

    /**
     * Sets the value of the results property.
     * 
     * @param value
     *     allowed object is
     *     {@link JAXBElement }{@code <}{@link ArrayOfEmploymentInformation }{@code >}
     *     
     */
    public void setResults(JAXBElement<ArrayOfEmploymentInformation> value) {
        this.results = value;
    }

И EmploymentInformation без геттеров и сеттеров

/**
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "EmploymentInformation", propOrder = {
    "arrearsSuspendedFrom",
    "arrearsSuspendedTo",
    "beneSeniority",
    "deceased",
    "deceasedDate",
    "earlyRetirement",
    "employeeIdentifier",
    "employmentStatus",
    "fmlaCode",
    "hcsoEndDate",
    "hcsoNotCovered",
    "hcsoStartDate",
    "job",
    "jobStart",
    "lastHire",
    "lastPerfReview",
    "lastSalaryReview",
    "leaveReason",
    "nextPerfReview",
    "nextSalaryReview",
    "originalHire",
    "ptoSuspendedFrom",
    "ptoSuspendedTo",
    "payAutomatically",
    "paySuspendedFrom",
    "paySuspendedTo",
    "roeIssueReason",
    "regularRetirement",
    "selfServiceProperties",
    "seniority",
    "statusAnticipatedEnd",
    "statusStartDate",
    "weeks"
})
public class EmploymentInformation {

    @XmlElement(name = "ArrearsSuspendedFrom")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar arrearsSuspendedFrom;
    @XmlElement(name = "ArrearsSuspendedTo")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar arrearsSuspendedTo;
    @XmlElement(name = "BeneSeniority")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar beneSeniority;
    @XmlElement(name = "Deceased")
    protected Boolean deceased;
    @XmlElement(name = "DeceasedDate")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar deceasedDate;
    @XmlElement(name = "EarlyRetirement")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar earlyRetirement;
    @XmlElementRef(name = "EmployeeIdentifier", namespace = "http://www.ultipro.com/contracts", type = JAXBElement.class)
    protected JAXBElement<EmployeeIdentifier> employeeIdentifier;
    @XmlElementRef(name = "EmploymentStatus", namespace = "http://www.ultipro.com/contracts", type = JAXBElement.class)
    protected JAXBElement<String> employmentStatus;
    @XmlElementRef(name = "FMLA_Code", namespace = "http://www.ultipro.com/contracts", type = JAXBElement.class)
    protected JAXBElement<String> fmlaCode;
    @XmlElement(name = "HCSOEndDate")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar hcsoEndDate;
    @XmlElement(name = "HCSONotCovered")
    protected Boolean hcsoNotCovered;
    @XmlElement(name = "HCSOStartDate")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar hcsoStartDate;
    @XmlElementRef(name = "Job", namespace = "http://www.ultipro.com/contracts", type = JAXBElement.class)
    protected JAXBElement<String> job;
    @XmlElement(name = "JobStart")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar jobStart;
    @XmlElement(name = "LastHire")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar lastHire;
    @XmlElement(name = "LastPerfReview")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar lastPerfReview;
    @XmlElement(name = "LastSalaryReview")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar lastSalaryReview;
    @XmlElementRef(name = "LeaveReason", namespace = "http://www.ultipro.com/contracts", type = JAXBElement.class)
    protected JAXBElement<String> leaveReason;
    @XmlElement(name = "NextPerfReview")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar nextPerfReview;
    @XmlElement(name = "NextSalaryReview")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar nextSalaryReview;
    @XmlElement(name = "OriginalHire")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar originalHire;
    @XmlElement(name = "PTOSuspendedFrom")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar ptoSuspendedFrom;
    @XmlElement(name = "PTOSuspendedTo")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar ptoSuspendedTo;
    @XmlElement(name = "PayAutomatically")
    protected Boolean payAutomatically;
    @XmlElement(name = "PaySuspendedFrom")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar paySuspendedFrom;
    @XmlElement(name = "PaySuspendedTo")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar paySuspendedTo;
    @XmlElementRef(name = "ROEIssueReason", namespace = "http://www.ultipro.com/contracts", type = JAXBElement.class)
    protected JAXBElement<String> roeIssueReason;
    @XmlElement(name = "RegularRetirement")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar regularRetirement;
    @XmlElementRef(name = "SelfServiceProperties", namespace = "http://www.ultipro.com/contracts", type = JAXBElement.class)
    protected JAXBElement<ArrayOfKeyValueOfstringstring> selfServiceProperties;
    @XmlElement(name = "Seniority")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar seniority;
    @XmlElement(name = "StatusAnticipatedEnd")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar statusAnticipatedEnd;
    @XmlElement(name = "StatusStartDate")
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar statusStartDate;
    @XmlElement(name = "Weeks")
    protected Double weeks;


}

2 ответа

Вам нужно сделать: Gson gson = new GsonBuilder() .registerTypeAdapter(JAXBElement.class, new JAXBElementAdapter()) .create();

Я не совсем уверен, почему ваш код не работает. Я думаю, что наиболее вероятная проблема заключается в том, что JAXBElement является параметризованным типом, поэтому вам нужно указать его с помощью параметра универсального типа.

Попробуйте вместо этого при регистрации вашего TypeAdapter:

gsonBuilder.registerTypeAdapter(
       new TypeToken<JAXBElement<String>>(){}.getType(),
       new JAXBElementAdapter());
Другие вопросы по тегам