有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JAXb在解组期间未填充对象

在这一点上我有点不知所措。我决不是SOAP/JAXb专家,但是,我正在尝试创建一个通用类,它将为任何服务封送/调用/解组。我使用天气服务wsdl作为起点来证明这个概念

我终于让编组、调用和解编能够无误地执行,但是,没有填充响应对象。有人能帮我找出我做错了什么吗?我也在寻找一个很好的解释,如果可能的话,这样我可以从这个经验中学习

同样,执行时没有错误。问题是GetCityWeatherBySipResponse的值。GetCityWeatherBySipResult显示为null。我知道文档返回了正确的结果,因为结果打印输出如下:

结果打印输出:

<?xml version="1.0" encoding="UTF-8"?><GetCityWeatherByZIPResponse xmlns="http://ws.cdyne.com/WeatherWS/">
    <GetCityWeatherByZIPResult>
        <Success>true</Success>
        <ResponseText>City Found</ResponseText>
        <State>MO</State>
        <City>Saint Charles</City>
        <WeatherStationCity>Farmington</WeatherStationCity>
        <WeatherID>4</WeatherID>
        <Description>Sunny</Description>
        <Temperature>79</Temperature>
        <RelativeHumidity>47</RelativeHumidity>
        <Wind>CALM</Wind>
        <Pressure>30.00S</Pressure>
        <Visibility/>
        <WindChill/>
        <Remarks/>
    </GetCityWeatherByZIPResult>
</GetCityWeatherByZIPResponse>

Response: GetCityWeatherByZIPResult: null

测试Web服务: http://wsf.cdyne.com/WeatherWS/Weather.asmx

初始呼叫(通过JBehave完成):

@Given("I call the weather soap service")
public void givenICallTheWeatherSoapService() {
    GetCityWeatherByZIP weather = new GetCityWeatherByZIP();
    weather.setZIP("63304");
    try {
        new WeatherTools();
        WeatherSoap weatherSoap = new WeatherSoap();
        GetCityWeatherByZIPResponse response = weatherSoap.getCityWeatherByZip("63304");
        System.out.println("Response: " + response);
    } catch (JAXBException | ParserConfigurationException | SOAPException | IOException e) {
        Assert.fail(e.getMessage());
    }
}

Soap服务类:

public class WeatherSoap extends PTFSoapClient {

    public WeatherSoap() throws JAXBException, ParserConfigurationException, SOAPException {
        super(PTFApplication.getConfig(Environment.executionEnv.getEnv(), "Weather SOAP endpoint"));
    }

    public GetCityWeatherByZIPResponse getCityWeatherByZip(String zip) throws JAXBException, SOAPException, IOException {
        GetCityWeatherByZIP weatherByZip = new GetCityWeatherByZIP();
        weatherByZip.setZIP(zip);
        try {
            sendRequest(weatherByZip);
            return (GetCityWeatherByZIPResponse) unmarshallResponse(GetCityWeatherByZIPResponse.class);
        } catch (ParserConfigurationException | XMLStreamException e) {
            e.printStackTrace();
            return null;
        }
    }
}

用于泛化调用的基本框架类(可用于所有SOAP调用):

public class PTFSoapClient {
    private JAXBContext context;
    private Marshaller marshaller;
    private Object object;
    private SOAPMessage message;
    private String endpoint;
    private SOAPMessage response;

    public PTFSoapClient(String endpoint) {
        this.endpoint = endpoint;
    }

    public void toConsole() throws JAXBException, SOAPException, IOException {
        message.writeTo(System.out);
        System.out.print("\n");
    }

    public SOAPMessage sendRequest(Object obj) throws JAXBException, ParserConfigurationException, SOAPException {
        object = obj;
        context = JAXBContext.newInstance(obj.getClass());
        marshaller = context.createMarshaller();

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        Document doc = dbf.newDocumentBuilder().newDocument();
        marshaller.marshal(object,doc);
        MessageFactory factory = MessageFactory.newInstance();
        message = factory.createMessage();
        message.getSOAPBody().addDocument(doc);
        message.saveChanges();

        SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
        response = connection.call(message, endpoint);
        connection.close();

        try {
            System.out.println("Response:");
            response.writeTo(System.out);
            System.out.println("");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;
    }

    public Object unmarshallResponse(Class<?> classname) throws JAXBException, XMLStreamException, SOAPException, IOException {
        Document doc = response.getSOAPBody().extractContentAsDocument();
        try {
            System.out.println("Document: ");
            printDocument(doc, System.out);
            System.out.println("");
        } catch (TransformerException e) {
            e.printStackTrace();
        }

        Unmarshaller unmarshaller = JAXBContext.newInstance(classname).createUnmarshaller();
        return unmarshaller.unmarshal(doc);
    }

    public static void printDocument(Document doc, OutputStream out) throws IOException, TransformerException {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        transformer.transform(new DOMSource(doc), 
             new StreamResult(new OutputStreamWriter(out, "UTF-8")));
    }
}

基本解组对象:

@XmlRootElement(name = "GetCityWeatherByZIPResponse",
                namespace = "http://ws.cdyne.com/WeatherWS/")
public class GetCityWeatherByZIPResponse {
    GetCityWeatherByZIPResult GetCityWeatherByZIPResult;

    public GetCityWeatherByZIPResult getGetCityWeatherByZIPResult() {
        return GetCityWeatherByZIPResult;
    }

    public void setGetCityWeatherByZIPResult(GetCityWeatherByZIPResult GetCityWeatherByZIPResult) {
        this.GetCityWeatherByZIPResult = GetCityWeatherByZIPResult;
    }

    @Override
    public String toString() {
        return "GetCityWeatherByZIPResult: " + GetCityWeatherByZIPResult;
    }
}

子umarshal对象:

public class GetCityWeatherByZIPResult {
    boolean Success;
    String ResponseText;
    String State;
    String City;
    String WeatherStationCity;
    String WeatherID;
    String Description;
    int Temperature;
    int RelativeHumidity;
    String Wind;
    String Pressure;
    String Visibility;
    String WindChill;
    String Remarks;

    public boolean isSuccess() {
        return Success;
    }

    public void setSuccess(boolean success) {
        Success = success;
    }

    public String getResponseText() {
        return ResponseText;
    }

    public void setResponseText(String responseText) {
        ResponseText = responseText;
    }

    public String getState() {
        return State;
    }

    public void setState(String state) {
        State = state;
    }

    public String getCity() {
        return City;
    }

    public void setCity(String city) {
        City = city;
    }

    public String getWeatherStationCity() {
        return WeatherStationCity;
    }

    public void setWeatherStationCity(String weatherStationCity) {
        WeatherStationCity = weatherStationCity;
    }

    public String getWeatherID() {
        return WeatherID;
    }

    public void setWeatherID(String weatherID) {
        WeatherID = weatherID;
    }

    public String getDescription() {
        return Description;
    }

    public void setDescription(String description) {
        Description = description;
    }

    public int getTemperature() {
        return Temperature;
    }

    public void setTemperature(int temperature) {
        Temperature = temperature;
    }

    public int getRelativeHumidity() {
        return RelativeHumidity;
    }

    public void setRelativeHumidity(int relativeHumidity) {
        RelativeHumidity = relativeHumidity;
    }

    public String getWind() {
        return Wind;
    }

    public void setWind(String wind) {
        Wind = wind;
    }

    public String getPressure() {
        return Pressure;
    }

    public void setPressure(String pressure) {
        Pressure = pressure;
    }

    public String getVisibility() {
        return Visibility;
    }

    public void setVisibility(String visibility) {
        Visibility = visibility;
    }

    public String getWindChill() {
        return WindChill;
    }

    public void setWindChill(String windChill) {
        WindChill = windChill;
    }

    public String getRemarks() {
        return Remarks;
    }

    public void setRemarks(String remarks) {
        Remarks = remarks;
    }
}

共 (1) 个答案

  1. # 1 楼答案

    你当前的地图

    @XmlRootElement注释上指定namespace属性时,它仅适用于该元素

    @XmlRootElement(name = "GetCityWeatherByZIPResponse",
                    namespace = "http://ws.cdyne.com/WeatherWS/")
    public class GetCityWeatherByZIPResponse {
    

    您的XML文档

    XML文档指定了一个默认名称空间。这意味着没有另一个显式名称空间映射的所有元素也是http://ws.cdyne.com/WeatherWS/名称空间的一部分

    <?xml version="1.0" encoding="UTF-8"?><GetCityWeatherByZIPResponse xmlns="http://ws.cdyne.com/WeatherWS/">
        <GetCityWeatherByZIPResult>
            <Success>true</Success>
    

    名称空间修复

    您需要在包级别指定名称空间映射,以便它应用于所有元素映射。这是使用名为@XmlSchema的特定类上的包级@XmlSchema注释来完成的

    @XmlSchema( 
        namespace = "http://ws.cdyne.com/WeatherWS/", 
        elementFormDefault = XmlNsForm.QUALIFIED) 
    package example;
    
    import javax.xml.bind.annotation.XmlNsForm;
    import javax.xml.bind.annotation.XmlSchema;
    

    了解更多信息

    我在博客上写了更多关于JAXB和名称空间限定的内容:


    更新

    默认元素名

    属性的默认元素与XML不匹配。对于下面的属性,预期的元素名称将为getCityWeatherByZIPResult,因此需要使用@XmlElement注释覆盖默认值

    @XmlElement(name="GetCityWeatherByZIPResult")
    public GetCityWeatherByZIPResult getGetCityWeatherByZIPResult() {
        return GetCityWeatherByZIPResult;
    }
    

    调试提示

    当遇到解组问题时,填充对象模型并对其进行编组,以查看基于当前映射的预期XML是什么