我有一个带有注释 nillable=true 的变量的类,我不希望它们出现在 xml 中。该类是从无法更改的 xsd 生成的。
例子: 一个看起来像这样的类:
public class Hi {
...
@XmlElement(name = "hello", nillable = true)
protected Long hello;
...
}
对象被 JAXBContext 创建的编码器编码。生成的xml变成:
...
<hello xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
...
Hi 类是从无法更改的 xsd 生成的。我的问题是,如果“hello”为空,是否有办法让编码器忽略可空参数并且不向 xml 输出任何内容?
最佳答案
一种方法是实现 decorator XMLStreamWriter 类型并在其中实现您的过滤器。
这是一个非常基本和幼稚的(它没有涵盖很多东西,比如命名空间和许多其他东西),它可以适用于你的情况,但它并不意味着完美,它只是为了展示想法:
public class FilteredXMLStreamWriter implements XMLStreamWriter {
private final XMLStreamWriter writer;
private final Set<String> pathsToSkip;
private final Stack<String> path = new Stack<>();
private boolean ignore;
public FilteredXMLStreamWriter(XMLStreamWriter writer, Set<String> pathsToSkip) {
this.writer = writer;
this.pathsToSkip = pathsToSkip;
}
/**
* Build the current path from the Stack
*/
private String toPath() {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String element : path) {
if (first) {
first = false;
} else {
sb.append('/');
}
sb.append(element);
}
return sb.toString();
}
public void writeStartElement(String prefix, String localName, String namespaceURI)
throws XMLStreamException {
// Add the current
path.push(localName);
if (!ignore) {
this.ignore = pathsToSkip.contains(toPath());
if (!ignore) {
this.writer.writeStartElement(prefix, localName, namespaceURI);
}
}
}
...
public void writeEndElement() throws XMLStreamException {
if (ignore) {
this.ignore = !pathsToSkip.contains(toPath());
} else {
this.writer.writeEndElement();
}
path.pop();
}
...
public void writeCharacters(String text) throws XMLStreamException {
if (!ignore) {
this.writer.writeCharacters(text);
}
}
public void writeCharacters(char[] text, int start, int len)
throws XMLStreamException {
if (!ignore) {
this.writer.writeCharacters(text, start, len);
}
}
...
}
这是一种让路径跳过的简单方法:
private static Set<String> pathsToSkip(Class<?> clazz) {
// Make sure that the class is annotated with XmlRootElement
XmlRootElement rootElement = clazz.getAnnotation(XmlRootElement.class);
if (rootElement == null) {
throw new IllegalArgumentException("XmlRootElement is missing");
}
// Create the root name from the annotation or from the class name
String rootName = ("##default".equals(rootElement.name()) ?
clazz.getSimpleName().substring(0, 1).toLowerCase() + clazz.getSimpleName().substring(1) :
rootElement.name());
// Set that will contain all the paths
Set<String> pathsToSkip = new HashSet<>();
addPathsToSkip(rootName, clazz, pathsToSkip);
return pathsToSkip;
}
private static void addPathsToSkip(String parentPath, Class<?> clazz,
Set<String> pathsToSkip) {
// Iterate over all the fields
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
XmlElement xmlElement = field.getAnnotation(XmlElement.class);
if (xmlElement != null) {
// Create the name of the element from the annotation or the field name
String elementName = ("##default".equals(xmlElement.name()) ?
field.getName() :
xmlElement.name());
String path = parentPath + "/" + elementName;
if (xmlElement.nillable()) {
// It is nillable so we add it to the paths to skip
pathsToSkip.add(path);
} else {
// It is not nillable so we check the fields corresponding
// to the field type
addPathsToSkip(path, field.getType(), pathsToSkip);
}
}
}
}
然后这里是你将如何调用它:
marshaller.marshal(
myObject,
new FilteredXMLStreamWriter(
XMLOutputFactory.newInstance().createXMLStreamWriter(sw),
pathsToSkip(Hi.class)
)
);
关于java - JAXB 编码,忽略 nillable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39204125/
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我正在使用ruby1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr
我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我想这样组织C源代码:+/||___+ext||||___+native_extension||||___+lib||||||___(Sourcefilesarekeptinhere-maycontainsub-folders)||||___native_extension.c||___native_extension.h||___extconf.rb||___+lib||||___(Rubysourcecode)||___Rakefile我无法使此设置与mkmf一起正常工作。native_extension/lib中的文件(包含在native_extension.c中)将被完全忽略。
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/