##前言
因项目需要,需要将一个复杂的对象(包括对象及对象集合)转化为json,xml.并组装通过HttpClient发送post请求的json,xml,soap格式报文。在解析xml时选择采用JAXB,能够使用Jackson对JAXB注解的支持实现(jackson-module-jaxb-annotations),既方便生成XML,也方便生成JSON。
##dto对象(包括对象以及对象集合)
《一》相关注解详解:
①:@XmlRootElement(name = “orderRelease”) 注解是指定xml的根节点,作用在类上
②:@XmlAccessorType
@XmlAccessorType 用于指定有java对象生成xml文件时对java对象属性的访问方式。 它的属性值是XmlAccessType的四个枚举值。分别是:
XmlAccessType.FIELD
其中XmlAccessType.FIELD java 对象中的所有成员变量
XmlAccessType.PROPERTY java对象中所有通过getter/setter 方式访问的成员变量。
XmlAccessType.PUBLIC_MEMBER java 对象中所有的public 访问权限的成员变量和通过getter/setter方式访问的成员变量 。
XmlAccessType.NONE java对象的所有属性都不映射为XML元素
(注:在我们这里我只用到了XmlAccessType.FIELD)
③:@XmlType(propOrder = { “orderMain”, “orderItemList”}) 因为xml在默认情况下,Jaxb编组出来的xml中的字段顺序是随机的,你可以使用@XmlType的propOrder属性来指定序列化的顺序。
④:@XmlElement该注解用在java类的属性上。用于将属性映射为xml的子节点,可通过在后面配置name属性值类改变java属性在xml文件中的名称。例如:
@XmlElement(name = "orderMain")
private OrderMain orderMain;
@XmlElementWrapper(name="orderItems")
@XmlElement(name = "orderItem")
private List orderItemList;
最后需要注意的是集合以及子对象里也会用到上述注解,请大家自行查看。
⑤:@XmlAccessorOrder
用于对java 对象生成的xml元素进行排序。它有两个属性值:
AccessorOrder.ALPHABETICAL:对生成的xml元素按字母顺序排序;
XmlAccessOrder.UNDEFINED:不排序
⑥:@XmlTransient
用于标示在由java对象映射xml时,忽略此属性。即,在生成的xml文件中不出现此元素。
⑦:@XmlElementWrapper
在注解最外面再加一层,可用于POJO中包含List的属性中
《二》dto对象(省略get,set方法)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "orderRelease")
@XmlType(propOrder = { "orderMain", "orderItemList","projectCode"})
public class OrderRelease {
@XmlElement(name = "orderMain")
private OrderMain orderMain;
@XmlElementWrapper(name="orderItems")
@XmlElement(name = "orderItem")
private List orderItemList;
@XmlElement(name = "projectCode")
private String projectCode;
《三》dto对象里的javaBean对象(省略get,set)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = {"id","messageId","orderName","orderCode","orderRemark","orderPublishTime","orderPublishTimeBegin","orderPublishTimeEnd","createUserName","createUserCode","orderTotalPrice","arriveTime","arriveTimeBegin","arriveTimeEnd","addressUserName","addressName","addressPhone","supplierId","supplierName","supplierUserName","supplierPhone","orderSource","projectName","cargoDismantleComment"})
public class OrderMain implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @描述:主键id
* @字段:id BIGINT(19)
*/
@XmlElement
private Long id;
/**
* @描述:消息ID
* @字段:message_id BIGINT(19)
*/
@XmlElement
private Long messageId;
/**
* @描述:订单名称
* @字段:order_name VARCHAR(100)
*/
@XmlElement
private String orderName;
/**
* @描述:订单编号
* @字段:order_code VARCHAR(50)
*/
@XmlElement
private String orderCode;
/**
* @描述:订单备注
* @字段:order_remark VARCHAR(500)
*/
@XmlElement
private String orderRemark;
/**
* @描述:订单发布时间
* @字段:order_publish_time DATETIME(19)
*/
@XmlElement
@XmlJavaTypeAdapter(DefaultDateXmlAdapter.class)
private java.util.Date orderPublishTime;
/** 非数据库字段,查询时使用 */
@XmlElement
@XmlJavaTypeAdapter(DefaultDateXmlAdapter.class)
private java.util.Date orderPublishTimeBegin;
/** 非数据库字段,查询时使用 */
@XmlElement
@XmlJavaTypeAdapter(DefaultDateXmlAdapter.class)
private java.util.Date orderPublishTimeEnd;
/**
* @描述:创建人姓名
* @字段:create_user_name VARCHAR(30)
*/
@XmlElement
private String createUserName;
/**
* @描述:创建人编码
* @字段:create_user_code VARCHAR(30)
*/
@XmlElement
private String createUserCode;
/**
* @描述:子订单的订单总额
* @字段:order_total_price DECIMAL(30)
*/
@XmlElement
private java.math.BigDecimal orderTotalPrice;
/**
* @描述:要求收货时间
* @字段:arrive_time DATE(10)
*/
@XmlElement
@XmlJavaTypeAdapter(DefaultDateXmlAdapter.class)
private java.util.Date arriveTime;
/** 非数据库字段,查询时使用 */
@XmlElement
@XmlJavaTypeAdapter(DefaultDateXmlAdapter.class)
private java.util.Date arriveTimeBegin;
/** 非数据库字段,查询时使用 */
@XmlElement
@XmlJavaTypeAdapter(DefaultDateXmlAdapter.class)
private java.util.Date arriveTimeEnd;
/**
* @描述:收货人名称
* @字段:address_user_name VARCHAR(30)
*/
@XmlElement
private String addressUserName;
/**
* @描述:收货地址
* @字段:address_name VARCHAR(200)
*/
@XmlElement
private String addressName;
/**
* @描述:收货人手机
* @字段:address_phone VARCHAR(100)
*/
@XmlElement
private String addressPhone;
/**
* @描述:供应商id
* @字段:supplier_id BIGINT(19)
*/
@XmlElement
private Long supplierId;
/**
* @描述:供应商名称
* @字段:supplier_name VARCHAR(200)
*/
@XmlElement
private String supplierName;
/**
* @描述:供应商联系人名称
* @字段:supplier_user_name VARCHAR(100)
*/
@XmlElement
private String supplierUserName;
/**
* @描述:供应商联系方式
* @字段:supplier_phone VARCHAR(50)
*/
@XmlElement
private String supplierPhone;
/**
* @描述:订单来源(1采购项目,2招标项目,3竞价项目,4合同,5新建,6订单)
* @字段:order_source TINYINT(3)
*/
@XmlElement
private Integer orderSource;
/**
* @描述:项目名称
* @字段:project_name VARCHAR(2000)
*/
@XmlElement
private String projectName;
/**
* @描述:拆分要求
* @字段:cargo_dismantle_comment VARCHAR(500)
*/
@XmlElement
private String cargoDismantleComment;
《四》dto对象里的javaBean对象(省略get,set)
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = {"id","messageId","orderCode","name","code","spec","techParameters","unitName","purchaseAmount","quoteUnitPrice","quoteTotalPrice","needTime","needTimeBegin","needTimeEnd","comment","itemComment","useDept","purpose","dataSourceProjectName","companyName","appliedEnterprise","appliedPersonAndPhone","erpItemId","userData","erpPlanCode"})
public class OrderItem implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @描述:主键 自动增长
* @字段:id BIGINT(19)
*/
@XmlElement
private Long id;
/**
* @描述:消息ID
* @字段:message_id BIGINT(19)
*/
@XmlElement
private Long messageId;
/**
* @描述:订单编号
* @字段:order_code VARCHAR(50)
*/
@XmlElement
private String orderCode;
/**
* @描述:采购品名称
* @字段:name VARCHAR(200)
*/
@XmlElement
private String name;
/**
* @描述:采购品编码
* @字段:code VARCHAR(20)
*/
@XmlElement
private String code;
/**
* @描述:采购品规格
* @字段:spec VARCHAR(500)
*/
@XmlElement
private String spec;
/**
* @描述:技术参数
* @字段:tech_parameters VARCHAR(500)
*/
@XmlElement
private String techParameters;
/**
* @描述:采购品单位(如 吨等)
* @字段:unit_name VARCHAR(10)
*/
@XmlElement
private String unitName;
/**
* @描述:采购品数量,来源于项目中可生成的采购品数量
* @字段:purchase_amount DECIMAL(20)
*/
@XmlElement
private java.math.BigDecimal purchaseAmount;
/**
* @描述:单价
* @字段:quote_unit_price DECIMAL(20)
*/
@XmlElement
private java.math.BigDecimal quoteUnitPrice;
/**
* @描述:
* @字段:quote_total_price DECIMAL(20)
*/
@XmlElement
private java.math.BigDecimal quoteTotalPrice;
/**
* @描述:需求日期
* @字段:need_time DATETIME(19)
*/
@XmlElement
@XmlJavaTypeAdapter(DefaultDateXmlAdapter.class)
private java.util.Date needTime;
/** 非数据库字段,查询时使用 */
@XmlElement
@XmlJavaTypeAdapter(DefaultDateXmlAdapter.class)
private java.util.Date needTimeBegin;
/** 非数据库字段,查询时使用 */
@XmlElement
@XmlJavaTypeAdapter(DefaultDateXmlAdapter.class)
private java.util.Date needTimeEnd;
/**
* @描述:备注
* @字段:comment VARCHAR(1000)
*/
@XmlElement
private String comment;
/**
* @描述:采购品备注
* @字段:item_comment VARCHAR(500)
*/
@XmlElement
private String itemComment;
/**
* @描述:使用单位
* @字段:use_dept VARCHAR(256)
*/
@XmlElement
private String useDept;
/**
* @描述:用途
* @字段:purpose VARCHAR(500)
*/
@XmlElement
private String purpose;
/**
* @描述:来源项目名称
* @字段:data_source_project_name VARCHAR(200)
*/
@XmlElement
private String dataSourceProjectName;
/**
* @描述:采购商名称
* @字段:company_name VARCHAR(200)
*/
@XmlElement
private String companyName;
/**
* @描述:申报企业
* @字段:applied_enterprise VARCHAR(256)
*/
@XmlElement
private String appliedEnterprise;
/**
* @描述:申报人、电话
* @字段:applied_person_and_phone VARCHAR(100)
*/
@XmlElement
private String appliedPersonAndPhone;
/**
* @描述:
* @字段:erp_item_id VARCHAR(50)
*/
@XmlElement
private String erpItemId;
/**
* @描述:用户自定义字段
* @字段:user_data VARCHAR(255)
*/
@XmlElement
private String userData;
/**
* @描述:
* @字段:erp_plan_code VARCHAR(50)
*/
@XmlElement
private String erpPlanCode;
##发送post请求的工具类
public class DefaultHttpManager{
public String post(String url, String content, String contentType) {
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
//设置参数到请求对象中
httpPost.setEntity(new StringEntity(JSON.toJSONString(content), Charset.forName("UTF-8")));
//设置header信息
httpPost.setHeader("Content-type", contentType);
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
String result = null;
try {
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
result = EntityUtils.toString(entity, Charset.forName("UTF-8"));
}
EntityUtils.consume(entity);
//释放链接
response.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
##dto转化为json格式数据的工具类及测试
《1》 工具类
public class JsonUtils {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 将对象转换成json字符串。
* Title: pojoToJson
* Description:
*
* @param data
* @return
*/
public static String objectToJson(Object data) {
try {
String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
《2》测试类
public static void main(String[] args) throws Exception {
OrderRelease orderRelease = new OrderRelease();
OrderMain orderMain = new OrderMain();
orderMain.setId(1L);
orderMain.setMessageId(123445L);
orderMain.setAddressName("苏黎");
orderMain.setAddressPhone("18736478526");
orderMain.setAddressUserName("苏黎");
orderMain.setArriveTime(new Date());
orderMain.setArriveTimeBegin(new Date());
orderMain.setArriveTimeEnd(new Date());
orderMain.setCargoDismantleComment("供应商拆分");
orderMain.setCreateUserCode("无所谓");
orderMain.setCreateUserName("苏黎");
orderMain.setOrderCode("DD7984654");
orderMain.setOrderName("走一个订单流程");
orderMain.setOrderPublishTime(new Date());
orderMain.setOrderRemark("此订单乃是流程第一个");
orderMain.setOrderSource(1);
orderMain.setOrderTotalPrice(new BigDecimal(1500));
orderMain.setProjectName("采购计划101");
orderMain.setSupplierId(1157358L);
orderMain.setSupplierName("岩式集团");
orderMain.setSupplierPhone("15536841259");
orderMain.setSupplierUserName("魏先生");
List list = new ArrayList<>();
OrderItem o = new OrderItem();
o.setName("沥青");
o.setCode("code154587");
o.setMessageId(123445L);
o.setUserData("自定义");
OrderItem o1 = new OrderItem();
o1.setName("焦油");
o1.setCode("code154588");
o1.setMessageId(123445L);
o1.setUserData("自定义");
list.add(o);
list.add(o1);
orderRelease.setOrderMain(orderMain);
orderRelease.setOrderItemList(list);
String result = JsonUtils.objectToJson(orderRelease);
DefaultHttpManager s= new DefaultHttpManager();
String a= s.post("http://localhost:8080/demo/ceShi",result, APPLICATION_JSON_UTF8_VALUE);
System.out.print(a);
}
《3》打印结果
##dto转化为xml格式数据的工具类及测试
《1》工具类
public class xmlUtils {
public static final String DEFAULT_ENCODING = "UTF-8";
/**
* pojo转换成xml 默认编码UTF-8
*
* @param obj 待转化的对象
* @return xml格式字符串
* @throws Exception JAXBException
*/
public static String convertToXml(Object obj) throws Exception {
return convertToXml(obj, DEFAULT_ENCODING);
}
/**
* pojo转换成xml
*
* @param obj 待转化的对象
* @param encoding 编码
* @return xml格式字符串
* @throws Exception JAXBException
*/
public static String convertToXml(Object obj, String encoding) throws Exception {
String result = null;
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
// 指定是否使用换行和缩排对已编组 XML 数据进行格式化的属性名称。
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
result = writer.toString();
return result;
}
}
《2》测试类
public static void main(String[] args) throws Exception {
OrderRelease orderRelease = new OrderRelease();
OrderMain orderMain = new OrderMain();
orderMain.setId(1L);
orderMain.setMessageId(123445L);
orderMain.setAddressName("苏黎");
orderMain.setAddressPhone("18736478526");
orderMain.setAddressUserName("苏黎");
orderMain.setArriveTime(new Date());
orderMain.setArriveTimeBegin(new Date());
orderMain.setArriveTimeEnd(new Date());
orderMain.setCargoDismantleComment("供应商拆分");
orderMain.setCreateUserCode("无所谓");
orderMain.setCreateUserName("苏黎");
orderMain.setOrderCode("DD7984654");
orderMain.setOrderName("走一个订单流程");
orderMain.setOrderPublishTime(new Date());
orderMain.setOrderRemark("此订单乃是流程第一个");
orderMain.setOrderSource(1);
orderMain.setOrderTotalPrice(new BigDecimal(1500));
orderMain.setProjectName("采购计划101");
orderMain.setSupplierId(1157358L);
orderMain.setSupplierName("岩式集团");
orderMain.setSupplierPhone("15536841259");
orderMain.setSupplierUserName("魏先生");
List list = new ArrayList<>();
OrderItem o = new OrderItem();
o.setName("沥青");
o.setCode("code154587");
o.setMessageId(123445L);
o.setUserData("自定义");
OrderItem o1 = new OrderItem();
o1.setName("焦油");
o1.setCode("code154588");
o1.setMessageId(123445L);
o1.setUserData("自定义");
list.add(o);
list.add(o1);
orderRelease.setOrderMain(orderMain);
orderRelease.setOrderItemList(list);
String result = xmlUtils.convertToXml(orderRelease);
DefaultHttpManager s= new DefaultHttpManager();
String a= s.post("http://localhost:8080/demo/ceShi",result, APPLICATION_XML_VALUE);
System.out.print(a);
}
##dto转化为soap格式数据的工具类及测试
因soap格式报文主体部分与xml格式完全一样,故在此 使用xml的工具类,将soap格式的报文进行组装测试
《1》测试类
public static void main(String[] args) throws Exception {
OrderRelease orderRelease = new OrderRelease();
OrderMain orderMain = new OrderMain();
orderMain.setId(1L);
orderMain.setMessageId(123445L);
orderMain.setAddressName("苏黎");
orderMain.setAddressPhone("18736478526");
orderMain.setAddressUserName("苏黎");
orderMain.setArriveTime(new Date());
orderMain.setArriveTimeBegin(new Date());
orderMain.setArriveTimeEnd(new Date());
orderMain.setCargoDismantleComment("供应商拆分");
orderMain.setCreateUserCode("无所谓");
orderMain.setCreateUserName("苏黎");
orderMain.setOrderCode("DD7984654");
orderMain.setOrderName("走一个订单流程");
orderMain.setOrderPublishTime(new Date());
orderMain.setOrderRemark("此订单乃是流程第一个");
orderMain.setOrderSource(1);
orderMain.setOrderTotalPrice(new BigDecimal(1500));
orderMain.setProjectName("采购计划101");
orderMain.setSupplierId(1157358L);
orderMain.setSupplierName("岩式集团");
orderMain.setSupplierPhone("15536841259");
orderMain.setSupplierUserName("魏先生");
List list = new ArrayList<>();
OrderItem o = new OrderItem();
o.setName("沥青");
o.setCode("code154587");
o.setMessageId(123445L);
o.setUserData("自定义");
OrderItem o1 = new OrderItem();
o1.setName("焦油");
o1.setCode("code154588");
o1.setMessageId(123445L);
o1.setUserData("自定义");
list.add(o);
list.add(o1);
orderRelease.setOrderMain(orderMain);
orderRelease.setOrderItemList(list);
String result = xmlUtils.convertToXml(orderRelease);
StringBuilder soap = new StringBuilder(); //构造请求报文
soap.append("");
soap.append("");
soap.append(" ");
soap.append("");
soap.append("");
soap.append(result);
soap.append(" ");
soap.append(" ");
soap.append(" ");
String requestSoap = soap.toString();
DefaultHttpManager s = new DefaultHttpManager();
String a = s.post("http://localhost:8080/demo/ceShi", requestSoap, APPLICATION_XML_VALUE);
String r = StringEscapeUtils.unescapeXml(a);
System.out.print(r);
}
《2》打印结果