繁体   English   中英

从InputStream解组

[英]Unmarshall from an InputStream

我已经写了简单的对象给马歇尔。 我将其编组到StringWriter而不是文件中。 它工作正常,但我不确定如何解组。

这是我到目前为止编写的代码。

public static void main(String[] args) throws JAXBException, FileNotFoundException {
    JAXBContext context = JAXBContext.newInstance(Employee.class);
    Marshaller marshaller = context.createMarshaller();

    Employee employee = new Employee();
    employee.setId(1002);
    employee.setOccupation("Software Developer");
    employee.setSalary("56000");

    StringWriter writer = new StringWriter();

    marshaller.marshal(employee, writer);
    System.out.println("Object Marshalled Successfully");

    Conversion.unMarshallingObject();
}

public static void unMarshallingObject() throws JAXBException {
    StringWriter writer = new StringWriter();
    InputStream stream = new ByteArrayInputStream(writer.toString().getBytes());

    JAXBContext context = JAXBContext.newInstance(Employee.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();

    Employee employee = (Employee) unmarshaller.unmarshal(stream);

    System.out.println("Object unmarshalled successfully");
    System.out.println("**********************************");
    System.out.println(employee.getId() + " " + employee.getOccupation() + " " + employee.getSalary());

} 

有很多示例,但所有示例都通过一个文件。 我不要任何文件。 有可能这样做吗?

谢谢

根据文档,您可以从Reader解组,也可以从StringReader

 Employee employee = (Employee) unmarshaller.unmarshal(new StringReader(yourString));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM