我想将输出流转换为 String 对象 [英] I want to convert an output stream into String object
问题描述
我想将 OutputStream
转换为 String
对象.我在编组 JAXB 对象后返回了一个 OutputStream
对象.
对 jaxb 不是很熟悉,根据我能找到的内容,您可以使用
转换为字符串public String asString(JAXBContext pContext,对象 pObject)投掷JAXB异常{java.io.StringWriter sw = new StringWriter();Marshaller marshaller = pContext.createMarshaller();marshaller.setProperty(Marshaller.JAXB_ENCODING,UTF-8");marshaller.marshal(pObject, sw);返回 sw.toString();}
但我不确定是否有搅拌物体.还在找.
** 编辑
<块引用>编组一个非元素
另一个常见的用例是你有一个没有的对象@XmlRootElement 就可以了.JAXB 允许你像这样编组它:
marshaller.marshal( 新的 JAXBElement(
新的QName("","rootTag"),Point.class,new点(...)));
这将元素作为根元素,后跟内容的对象,然后.你实际上可以将它与一个类一起使用有@XmlRootElement,而且很简单重命名根元素名称.
第一眼第二个Point.class 参数可能看起来多余的,但实际上是必要的确定编组员是否会生产(臭名昭著的)@xsi:type.在这例如,类和实例是点,所以你不会看到@xsi:类型.但如果它们不同,你会看到的.
这也可以用来编组一个简单的对象,如 String 或整数.
marshaller.marshal( 新的 JAXBElement(
新的QName("","rootTag"),String.class,"foo酒吧"));
但不幸的是它不能用于编组像 List 或 Map 这样的对象,作为他们不是头等舱JAXB 世界的公民.
找到这里>
I want to convert an OutputStream
into a String
object. I am having an OutputStream
object returned after marshalling the JAXB object.
not very familiar with jaxb, from what i was able to find you can convert into a string using
public String asString(JAXBContext pContext,
Object pObject)
throws
JAXBException {
java.io.StringWriter sw = new StringWriter();
Marshaller marshaller = pContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.marshal(pObject, sw);
return sw.toString();
}
but I'm not sure about a stirng object. still searching.
** EDIT
Marshalling a non-element
Another common use case is where you have an object that doesn't have @XmlRootElement on it. JAXB allows you to marshal it like this:
marshaller.marshal( new JAXBElement(
new QName("","rootTag"),Point.class,new Point(...)));This puts the element as the root element, followed by the contents of the object, then . You can actually use it with a class that has @XmlRootElement, and that simply renames the root element name.
At the first glance the second Point.class parameter may look redundant, but it's actually necessary to determine if the marshaller will produce (infamous) @xsi:type. In this example, both the class and the instance are Point, so you won't see @xsi:type. But if they are different, you'll see it.
This can be also used to marshal a simple object, like String or an integer.
marshaller.marshal( new JAXBElement(
new QName("","rootTag"),String.class,"foo bar"));But unfortunately it cannot be used to marshal objects like List or Map, as they aren't handled as the first-class citizen in the JAXB world.
found HERE
这篇关于我想将输出流转换为 String 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!