当我序列化我的POJO时,一切都按预期工作。我得到这样的东西:
<?xml version='1.0' encoding='UTF-8'?>
<gsafeed>
...
</gsafeed>
收件人(Google Search Appliance)似乎希望XML包含这样的DTD:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE gsafeed PUBLIC "-//Google//DTD GSA Feeds//EN" "">
<gsafeed>
...
</gsafeed>
我怎样才能做到这一点?
答案 0 :(得分:2)
根据其他答案,遗憾的是没有办法以简单的方式实现这一目标。
长期可能有用的一件事是提交添加此类功能的请求 - 例如,通过特定于XML的ObjectWriter
公开这听起来是一个合理的功能。
答案 1 :(得分:1)
我经常鄙视杰克逊的问题答案,这些问题是&#34;编写自定义序列化程序&#34;因为通常有一种更简单,更清洁的方式。不幸的是,除了自定义序列化程序之外,我还不知道更好的方法来实现向序列化输出添加元数据。
希望有人回答一个更简单的解决方案,但这应该可以实现你想要实现的目标。
public class GsaFeedModule extends SimpleModule {
private static final String NAME = "GsaFeedModule";
public GsaFeedModule() {
super(NAME);
addSerializer(GsaFeed.class, new GsaFeedSerializer());
}
public static class GsaFeedSerializer extends JsonSerializer<GsaFeed> {
@Override
public void serialize(GsaFeed gsaFeed, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeRaw("<?xml version='1.0' encoding='UTF-8'?>");
jsonGenerator.writeRaw("<!DOCTYPE gsafeed PUBLIC \"-//Google//DTD GSA Feeds//EN\" \"\">");
jsonGenerator.writeStartObject();
// write fields
jsonGenerator.writeEndObject();
}
}
}
XmlMapper xm = new XmlMapper();
xm.registerModule(new GsaFeedModule());
答案 2 :(得分:1)
似乎没有一种优雅的方式来设置DTD。除了实现自定义序列化程序之外,您还可以考虑在XML生成器初始化之后覆盖XmlSerializerProvider
以写入DTD字符串写入。这是一个例子:
public class JacksonXmlDTD {
private static class DtdXmlSerializerProvider extends XmlSerializerProvider {
private final String dtd;
public DtdXmlSerializerProvider(
final XmlSerializerProvider src,
final SerializationConfig config,
final SerializerFactory jsf,
final String dtd) {
super(src, config, jsf);
this.dtd = dtd;
}
@Override
protected void _initWithRootName(final ToXmlGenerator xgen, final QName rootName)
throws IOException {
super._initWithRootName(xgen, rootName);
try {
xgen.getStaxWriter().writeDTD(dtd);
} catch (final XMLStreamException e) {
StaxUtil.throwXmlAsIOException(e);
}
}
@Override
public DefaultSerializerProvider createInstance(
final SerializationConfig config, final SerializerFactory jsf) {
return new DtdXmlSerializerProvider(this, config, jsf, dtd);
}
}
public static void main(String[] args) throws JsonProcessingException {
final XmlMapper xmlMapper = new XmlMapper();
xmlMapper.enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION);
final String dtd = "<!DOCTYPE gsafeed PUBLIC \"-//Google//DTD GSA Feeds//EN\" \"\">";
final DtdXmlSerializerProvider serializerProvider = new DtdXmlSerializerProvider(
(XmlSerializerProvider) xmlMapper.getSerializerProvider(),
xmlMapper.getSerializationConfig(),
xmlMapper.getSerializerFactory(),
dtd);
xmlMapper.setSerializerProvider(serializerProvider);
final Map<String, Object> map = new HashMap<>();
map.put("object", "value");
System.out.println(xmlMapper.writeValueAsString(map));
}
}
输出:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE gsafeed PUBLIC "-//Google//DTD GSA Feeds//EN" ""><HashMap xmlns=""><object>value</object></HashMap>