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

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

问题描述

我想将 OutputStream 转换为 String 对象。我在编组JAXB对象后返回了 OutputStream 对象。

I want to convert an OutputStream into a String object. I am having an OutputStream object returned after marshalling the JAXB object.

推荐答案

不太熟悉jaxb,从我能够找到你可以转换为字符串使用

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.

**编辑


编组非元素

Marshalling a non-element

另一个常见的用例是你
有一个没有
@XmlRootElement的对象。 JAXB允许你
像这样编组:

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(新的JAXBElement(

new
QName( ,rootTag),Point.class,new
Point(...)));

marshaller.marshal( new JAXBElement(
new QName("","rootTag"),Point.class,new Point(...)));

这将元素设为
root元素,然后是对象的内容
。你
实际上可以使用
有@XmlRootElement的类,而只需
重命名根元素名称。

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第一眼看到第二个
Point.class参数可能看起来是
冗余,但实际上需要
来确定编组器是否会产生
产生(臭名昭着)@xsi:type。在这个
的例子中,类和
实例都是Point,所以你不会看到
@xsi:type。但如果它们不同,你会看到

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.

这也可以用来编组一个
的简单对象,比如String或者
整数。

This can be also used to marshal a simple object, like String or an integer.

marshaller.marshal(新的JAXBElement(

new
QName(,rootTag), String.class,foo
bar));

marshaller.marshal( new JAXBElement(
new QName("","rootTag"),String.class,"foo bar"));

但不幸的是它不能用于
封送像List或Map这样的对象,因为
他们不是JAXB世界中一流的
公民。

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.

发现 HERE

这篇关于我想将输出流转换为String对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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