我想将输出流转换为 String 对象 [英] I want to convert an output stream into String object

查看:23
本文介绍了我想将输出流转换为 String 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 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();}

ws.apache.org

但我不确定是否有搅拌物体.还在找.

** 编辑

<块引用>

编组一个非元素

另一个常见的用例是你有一个没有的对象@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();
}

ws.apache.org

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆