我正在开发一个RESTful web服务。
我有很多实体类(主要是JPA实体,但也有其他bean)。
有大量的对象映射、序列化、绑定和诸如此类的库。我在找一个能让我:
Person可能有视图full和simple。当请求Person的Person视图时,只有属性id、firstName和lastName才会被序列化。当请求full视图时,属性mother和father (即Persons本身)也将被序列化,但只会使用simple视图(因此不会向祖父母推荐)。
JSON序列化必须是“自然”,即在Javascript中有意义的内容。这意味着我需要适当的整数、布尔值和空值,我也不想要额外的对象包装器或试图捕获整个XML的东西。
对于XML,必须可以将序列化配置为使用空元素来序列化空元素,而不是XML的xsi:nil="true"属性。
此外,必须使用嵌套元素序列化数组,以便区分空数组和给定视图中不存在的属性:- Undefined `friends` property (not present in view):-空数组,人没有朋友:
Person对象时,库应该:
Person.setLastName(“邦乔维”);person.setFriends(新ArrayList());
例如,它不应该触及实体firstName和/或清除它是father。
当然,对于列表,这应该更加复杂。我希望配置一个id属性,由它决定是更新嵌套实体还是创建一个新实体。
这些更新/补丁是库不能仅仅返回DTO的原因之一:因为那时null可能意味着"unset“或”什么都不做“。好了,就是这样。我已经说了很多“必须”,我现在意识到:)库实际上不需要提供这种功能,但是必须有一种方法以一种干净的方式添加功能(不要以一种使重写一切变得更容易的方式)。
发布于 2009-04-09 13:22:38
我不知道现有的库可以完成您需要的一切,但是,假设您需要实现一些东西:
- Look at using Apache Commons BeanUtils to be able to get all property values ([http://commons.apache.org/beanutils/](http://commons.apache.org/beanutils/)). In particular, the PropertyUtils class.
- Use BeanUtils recursively to walk your entire object graph - be careful of cycles - you'll need a Set or something on the side to keep track of what you've already seen
- XML: Look at XMLEncoder - it works using JavaBean properties to create XML
- I assume you already have some means of indexing the objects you want to merge into (like a Map of some sort)
- I assume you already have some means to know which property is the key that uniquely identifies an object (I assume last name is just to get the point across, as it would make a bad key)
- XML: For this type of use, I'd recommend a SAX reader for the xml - you'll need a stack to keep track of which objects you're adding data to. The SAX reader tells you what tags are seen and then gives the values for those tags. You could also use XML pull here, which tends to be a little faster
- JSON: take a look at some of the open source JSON libraries and do some tweaking. JSON is pretty simple to parse, and these tools tend to be pretty small so this shouldn't be a big deal. Alternatively, you could write an ANTLR (or other generator) parser to read the JSON and do with it as you like.
发布于 2011-01-13 00:39:50
无论它的价值是什么,杰克逊都有部分的即时更新:
ObjectMapper mapper = new ObjectMapper();
Bean existing = ...;
mapper.updatingReader(existing).readValue(jsonSource);它还可以转换兼容类型(类似于序列化到JSON,读取回不同类型)。
对于XML部分,您可以使用JAXB,但据我所知,它只能完成绑定。
https://stackoverflow.com/questions/731989
复制相似问题