java代码如何将对象转为xml呢?
下文笔者讲述xml转为对象的方法分享,如下所示
xml和对象之间相互转换 是我们日常开发中常常需面对的操作 那么如何实现xml和对象之间相互转换呢? 下文笔者将一一道来,如下所示
实现思路: 使用xmlRootElement Path,Produces注解 定义设置相关的xml元素 然后即可将类使用xml输出例: java对象转换为xml
/* * 这里是java265.com * 定义的java对象转换为xml的方法分享 */ package com.java265.rest.bean; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class User { private String userId; private String userName; private String age; public User() {}; public User(String userId, String userName, String age) { this.userId = userId; this.userName = userName; this.age = age; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } } package com.java265.rest.resources; import java.util.Arraylist; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import com.waylau.rest.bean.User; @Path("/users") public class UserResource { private static Map<String,User> userMap = new HashMap<String,User>();//存储用户 /** * 查询所有 * @return */ @GET @Produces(MediaType.APPLICATION_XML) public List<i></i>t<User> getAllUsers(){ List<User> users = new ArrayList<User>(); User u1 = new User("001","WayLau","26"); User u2 = new User("002","King","23"); User u3 = new User("003","Susan","21"); userMap.put(u1.getUserId(), u1); userMap.put(u2.getUserId(), u2); userMap.put(u3.getUserId(), u3); users.addAll( userMap.values() ); return users; } @GET @Path("/getUserXml") @Produces(MediaType.APPLICATION_XML) public User getUserXml() { User user = new User(); user.setAge("18"); user.setUserId("8888"); user.setUserName("maoxiaomao"); return user; } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。