首页 > 解决方案 > Jackson Mixin 不能在 Pojo 中工作到 json

问题描述

我的目标是 xml 到 Pojo 和 Pojo 到 json。我已经使用 jaxb 对 pojo 做了 xml。现在我正在尝试使用 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
}

如何删除名称、声明类型、范围、零、全局范围、类型替换 ang 获取以下 json

{
 "CompositeResponse":
 {
    "CompositeIndividualResponse" : [ {
      "ResponseMetadata" : {
        "ResponseCode" : "HS000000",
        "ResponseDescriptionText" : "Success"
      }
    } ]
  }
}

我在看这篇文章,但这对我不起作用。
我为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();
}

谁能帮助我哪里错了,该怎么办谢谢。

标签: javajsonxmljacksonjaxb

解决方案


实际上,我本周刚刚遇到了这个问题,并通过删除

AnnotationIntrospector introspector = new  JaxbAnnotationIntrospector(mapper.getTypeFactory());
              mapper.setAnnotationIntrospector(introspector );

片。我还没有回过头来研究如何将其添加回来,但这让您拥有的其余代码正确地为我工作,并且我不再看到 JAXBElement 包装器。


推荐阅读