Jaxb2 实现JavaBean与xml互转,android面试知识点

  1. t = (T) unmarshaller.unmarshal(new StringReader(xml));

  2. } catch (Exception e) {

  3. e.printStackTrace();

  4. }

  5. return t;

  6. }

  7. }

非常简单易懂,需要注意的是

Java代码   收藏代码

  1. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

  2. marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

Marshaller.JAXB_FORMATTED_OUTPUT 决定是否在转换成xml时同时进行格式化(即按标签自动换行,否则即是一行的xml)

Marshaller.JAXB_ENCODING xml的编码方式

另外,Marshaller 还有其他Property可以设置,可以去查阅api。

2、最简单转换

Java代码   收藏代码

  1. package t1;

  2. import java.util.Date;

  3. import javax.xml.bind.annotation.Xm
    lAccessType;

  4. import javax.xml.bind.annotation.XmlAccessorType;

  5. import javax.xml.bind.annotation.XmlAttribute;

  6. import javax.xml.bind.annotation.XmlElement;

  7. import javax.xml.bind.annotation.XmlRootElement;

  8. import javax.xml.bind.annotation.XmlType;

  9. /**

  10. * @author      zhuc

  11. * @create      2013-3-29 下午2:49:48

  12. */

  13. @XmlAccessorType(XmlAccessType.FIELD)

  14. @XmlRootElement

  15. @XmlType(name = “book”, propOrder = { “author”, “calendar”, “price”, “id” })

  16. public class Book {

  17. @XmlElement(required = true)

  18. private String author;

  19. @XmlElement(name = “price_1”, required = true)

  20. private float price;

  21. @XmlElement

  22. private Date calendar;

  23. @XmlAttribute

  24. private Integer id;

  25. /**

  26. * @return the author

  27. */

  28. public String getAuthor() {

  29. return author;

  30. }

  31. /**

  32. * @return the price

  33. */

  34. public float getPrice() {

  35. return price;

  36. }

  37. /**

  38. * @return the calendar

  39. */

  40. public Date getCalendar() {

  41. return calendar;

  42. }

  43. /**

  44. * @return the id

  45. */

  46. public Integer getId() {

  47. return id;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值