用于包装模型和/或转换模型 (POJO) 的良好 JAXB 设计模式?
我有以下模型,
class MyClass {
id
someRandomString
}
我想将此 POJO 返回给客户端...
<Root>
<random>if + randomstring</random>
</Root>
基本上我正在处理一个非常面向消息的服务,所以我需要将模型包装并转换为出站 XML 格式...同样继续输入端
我有这个XML...
<Root>
<Username>
<Password>
<Action> <-- Some action or service to perform
<SomeModel1>
<SomeModel2>
</Root>
所以root、用户名和密码是常量元素,而SomeModel可以根据“服务”进行更改
基本上我正在寻找一种XML与模型不匹配的设计模式需要有一个转变……
或者如果我做了...
class MyClass {
id
someRandomString
random
@XMLTransient
getId()
@XMLTransient
getSomeRandomString()
getRandom() {
return id + someRandomString
}
}
所以JAXB只会映射getRandom...
我的另一个想法是创建一堆代表最终输出的类,并将值设置为这些...
所以
class MyResponse {
randomString
status
someOtherFieldRequired in response
}
然后我可以做...
myResponse.setRandomString(myClass.getId() + myClass.getSomeRandomString());
I have the following model
class MyClass {
id
someRandomString
}
I would like to return this POJO to the client as...
<Root>
<random>if + randomstring</random>
</Root>
Basically I'm dealing with a very message oriented service so I need to wrap and transform the model to the outbound XML format... Same goes on the input side
I have this XML...
<Root>
<Username>
<Password>
<Action> <-- Some action or service to perform
<SomeModel1>
<SomeModel2>
</Root>
So the root and username and password are constant elements while the SomeModel can change based on the "service"
Bassically i'm looking for a design-pattern where the XML doesn't match the model and there needs to be a transformation to and from...
Or what if I did...
class MyClass {
id
someRandomString
random
@XMLTransient
getId()
@XMLTransient
getSomeRandomString()
getRandom() {
return id + someRandomString
}
}
So JAXB will only map getRandom...
Another idea I have is create a bunch of classes that will represent the final output and just set the values to thoses...
So
class MyResponse {
randomString
status
someOtherFieldRequired in response
}
and then I can do...
myResponse.setRandomString(myClass.getId() + myClass.getSomeRandomString());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 XmlAdapter 与 XmlJavaTypeAdapter,但我认为它可能需要您将 id 和 someRandomString 属性封装到一个单独的类中。如果可能的话,我不知道如何直接将元素值分散到两个单独的 bean 属性上。
You could use XmlAdapter in conjunction with XmlJavaTypeAdapter, but I think it might require you to encapsulate the id and someRandomString properties into a separate class. Spreading out an element value over two separate bean properties directly is not something I'd know how to do, if it is at all possible.
您可以使用
id
和someRandomString
字段来分隔元素,并使用样式表将元素合并为一个。 JAXB 提供了与javax.xml.transform
API 相匹配的JAXBSource
类:You could the
id
andsomeRandomString
fields to separate elements and use a style sheet to combine the elements into one. JAXB offers theJAXBSource
class that fits it with thejavax.xml.transform
APIs: