我正在开发一个已经使用XML序列化的项目,所以我需要一个优雅的解决方案来支持JSON,重用JAXB注释.
任何人都可以推荐一些能够很好地重用JAXB注释的Java JSON库吗?轻量级库是首选.
注意: 我是EclipseLink JAXB (MOXy) 的领导者,也是 JAXB ( JSR-222 ) 专家组的成员。
查看添加到 EclipseLink JAXB (MOXy) 的 JSON 绑定。我们不仅利用 JAXB 注释,还利用运行时 API:
package blog.json.twitter;
import java.util.Date;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(SearchResults.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setProperty("eclipselink.media.type", "application/json");
StreamSource source = new StreamSource("http://search.twitter.com/search.json?q=jaxb");
JAXBElement<SearchResults> jaxbElement = unmarshaller.unmarshal(source, SearchResults.class);
Result result = new Result();
result.setCreatedAt(new Date());
result.setFromUser("bdoughan");
result.setText("You can now use EclipseLink JAXB (MOXy) with JSON :)");
jaxbElement.getValue().getResults().add(result);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty("eclipselink.media.type", "application/json");
marshaller.marshal(jaxbElement, System.out);
}
}
Run Code Online (Sandbox Code Playgroud)
除了 JAXB 注释之外,还支持 MOXy 扩展(例如 @XmlPath),从而更容易拥有一种可用于 XML 和 JSON 的注释模型:
| 归档时间: |
|
| 查看次数: |
2852 次 |
| 最近记录: |