简体   繁体   English

Jackson处理器用于java bean到json \\ xml的序列化

[英]Jackson processor for java bean to json\xml serialization

Hi I am having a java bean and i need to serialize it to json. 嗨,我有一个java bean,我需要将它序列化为json。 For this purpose i am using the jackson processor which is very powerful. 为此我使用的是非常强大的杰克逊处理器。 But I also need to convert the java bean to XML. 但我还需要将java bean转换为XML。 Can this be achieved using the jackson processor ?? 这可以用杰克逊处理器实现吗? If yes then please provide with the links where I can get the examples. 如果是,那么请提供我可以获得示例的链接。 Thanks!!!! 谢谢!!!!

If you want to keep Jackson and JSON out of your pojos, you can create a translation layer that can translate to a JAXB object and use pure JAXB (JAXB being one possible implementation in this case). 如果你想让杰克逊和JSON远离你的pojos,你可以创建一个可以转换为JAXB对象并使用纯JAXB的转换层(在这种情况下JAXB是一种可能的实现)。 If your domain objects map straight to the rendered JSON or you can use mixins / PropertyNamingStrategy , you will need no annotations in your pojos. 如果您的域对象直接映射到渲染的JSON,或者您可以使用mixins / PropertyNamingStrategy ,则您的pojos中不需要注释。 I'm not sure if this is applicable in your situation but I know that many environments strive for this. 我不确定这是否适用于您的情况,但我知道许多环境都在努力解决这个问题。

Definitely! 非也! Jackson obviously has first-class support for JSON; 杰克逊显然拥有对JSON的一流支持; but there is also simple extension module to do "mini-JAXB": jackson-xml-databind . 但是还有一个简单的扩展模块来做“mini-JAXB”: jackson-xml-databind With Jackson's support for JAXB annotations (or not, if you just prefer Jackson's own annotations & xml module's couple additional ones), it's definitely possible to do both JSON and XML just using Jackson functionality. 有了Jackson对JAXB注释的支持(或者,如果你只是喜欢Jackson自己的注释和xml模块的另外几个注释),那么使用Jackson功能肯定可以同时使用JSON和XML。

I mostly recommend this for cases where XML support is a legacy thing (which is what most new services do). 对于XML支持是遗留物(大多数新服务都是这样)的情况,我主要推荐这种方法。 If XML is the main focus, it may make more sense to use JAXB. 如果XML是主要关注点,那么使用JAXB可能更有意义。 But even then I recommend against using conversion layers from XML to JSON; 但是即使如此,我还是建议不要使用从XML到JSON的转换层。 ones I have seen used have been plagues with issues when they conversion at data format layer, which IMO is completely wrong place to do it. 我所看到的那些在数据格式层进行转换时遇到了问题,IMO是完全错误的做法。 This is also why Jackson does not try converting JSON to XML (or vice versa); 这也是杰克逊不尝试将JSON转换为XML(反之亦然)的原因; rather, it only supports converting POJOs to/from external data formats. 相反,它仅支持将POJO与外部数据格式进行转换。

Yes it is possible. 对的,这是可能的。 You would need to annotate your Java bean using the JAXB annotations which will give you the XML marshalling and unmarshalling support. 您需要使用JAXB注释来注释Java bean,这将为您提供XML编组和解组支持。 Then, using Jackson's support for JAXB annotations you can go back and forth between Java and JSON. 然后,使用Jackson对JAXB注释的支持 ,您可以在Java和JSON之间来回切换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM