我的目标是从xml到Pojo,从Pojo到json。我已经使用jaxb将xml转换为pojo。现在我正在尝试使用jackson Jaxb从pojo到json。在那里我得到了下面的json,它在json中生成JXBElement类文件,如下所示。
{
"name" : "{http://xxx.xx.xx.xx.xx.xx.xx}CompositeResponse",
"declaredType" : "xxx.xx.xx.xx.xx.xx.xxCompositeResponseType",
"scope" : "javax.xml.bind.JAXBElement$GlobalScope",
"value" : {
"CompositeIndividualResponse" : [ {
"ResponseMetadata" : {
"ResponseCode" : "HS000000",
"ResponseDescriptionText" : "Success"
}
} ]
},
"nil" : false,
"globalScope" : true,
"typeSubstituted" : false
}
如何删除name、declaredType、scope、nil、globalScope、typeSubstituted并获得以下json
{
"CompositeResponse":
{
"CompositeIndividualResponse" : [ {
"ResponseMetadata" : {
"ResponseCode" : "HS000000",
"ResponseDescriptionText" : "Success"
}
} ]
}
}
我正在寻找这个post,但这对我不起作用。
下面是我为jackson mixin尝试过的代码。
public class Main {
public static interface JAXBElementMixinT {
@JsonValue
Object getValue();
}
public static void main(String[] args) throws XMLStreamException, IOException {
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
mapper.setAnnotationIntrospector(introspector );
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.addMixIn(JAXBElement.class, JAXBElementMixinT.class);
String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
System.out.println(result);
}
}
我也尝试了下面的代码,但没有成功。
public abstract class JAXBElementMixIn {
@JsonIgnore abstract String getScope();
@JsonIgnore abstract boolean isNil();
@JsonIgnore abstract boolean isGlobalScope();
@JsonIgnore abstract boolean isTypeSubstituted();
@JsonIgnore abstract Class getDeclaredType();
}
有人能帮我吗?我哪里错了?该怎么做?谢谢。
发布于 2019-06-11 10:00:10
我终于能够解决这个问题了。根据@Ryan answer,我不需要以下代码:AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory()); mapper.setAnnotationIntrospector(introspector );
但我必须添加JaxbAnnotationModule module = new JaxbAnnotationModule(); mapper.registerModule(module)
,否则杰克逊将为每个元素生成链接和元数据。完整的代码如下
public class Main {
public static interface JAXBElementMixinT {
@JsonValue
Object getValue();
}
public static void main(String[] args) throws XMLStreamException, IOException {
ObjectMapper mapper = new ObjectMapper();
JaxbAnnotationModule module = new JaxbAnnotationModule();
mapper.registerModule(module)
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.addMixIn(JAXBElement.class, JAXBElementMixinT.class);
String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employee);
System.out.println(result);
}
}
发布于 2019-06-11 03:26:44
事实上,这周我刚刚面对了这个问题,并通过删除
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
mapper.setAnnotationIntrospector(introspector );
一块。我还没有回头研究如何将它添加回来,但这样就可以让您的其余代码正确地为我工作,并且我不再看到JAXBElement包装器。
https://stackoverflow.com/questions/56530267
复制相似问题