【Java】接口开发中关于接受和发送json的相关范例
接受json
package com.suneee.scn.wms.web.rocketmq; import java.util.List; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import org.springframework.web.context.support.WebApplicationObjectSupport; import com.suneee.scn.common.exception.ScnException; import com.suneee.scn.message.model.MsgInfo; import com.suneee.scn.message.receive.MsgConsumerI; import com.suneee.scn.wms.consumer.impl.ItemMainConsumer; import com.suneee.scn.wms.dao.ItemMainDao; import com.suneee.scn.wms.model.dbo.Item; import com.suneee.scn.wms.model.dbo.ItemInterDO; import com.suneee.scn.wms.model.dbo.ItemMainDO; @Service("itemMessage") public class ItemMessage extends WebApplicationObjectSupport implements MsgConsumerI { private static final Logger log=LoggerFactory.getLogger(ItemMessage.class); @Autowired private ItemMainDao itemMainDao; private static ApplicationContext applicationContext = null; public static ApplicationContext getAppContext() { return applicationContext; } public static Object getBean(String name) { return applicationContext.getBean(name); } @Override protected void initApplicationContext(ApplicationContext context) { super.initApplicationContext(context); if(applicationContext == null){ applicationContext = context; } } @Override public boolean dealMsg(MsgInfo msg) { log.debug("send数据已经传过来了:"+msg.getData()); //{'request': {'enterpriseid': 55,'ownerCode': 'SunEee01', //'item': {'itemName': '熊孩子新疆无花果成品268g','itemType': 'ZC','barCode': '6924459400256',' shelfLife ': 0,'itemCode': 'xhzwhggcp_268'}}} //分解json JSONObject jsonObject = JSONObject.fromObject(msg.getData()); String request = jsonObject.getString("request"); JSONObject itemd = JSONObject.fromObject(request); String items = itemd.getString("item"); JSONObject item = JSONObject.fromObject(items); ItemMainDO the = new ItemMainDO(); the.setEnterpriseid(Long.valueOf(itemd.getInt("enterpriseid"))); the.setClientcode(itemd.getString("ownerCode")); the.setDescription(item.getString("itemName")); the.setItemnumber(item.getString("itemCode")); the.setItemtype(item.getString("itemType")); the.setDisplayitemnumber(item.getString("barCode")); the.setShelflife(item.getInt("shelfLife")); //获取对象 ItemMainConsumer itemMainComsumer = (ItemMainConsumer) applicationContext.getBean("itemMainConsumer"); int ok; try { ok = itemMainComsumer.insertItemMain(the); if(ok>0){ log.debug("商品同步成功!"); return true; }else if(ok==-1){ log.debug("商品【"+item.getString("itemName")+"】已经存在!"); return true; }else{ log.debug("商品同步失败!"); return false; } } catch (ScnException e) { e.printStackTrace(); } return true; }}
注意:
String items = itemd.getString("KEY");里面的itemd必须是JSONObject。
比如:
{'request': {'enterpriseid': 55,'ownerCode': 'SunEee01','item': {'itemName': '熊孩子新疆无花果成品268g','itemType': 'ZC','barCode': '6924459400256',' shelfLife ': 0,'itemCode': 'xhzwhggcp_268'}}}
JSONObject jsonObject = JSONObject.fromObject(msg.getData());---将json的整个string字符串转为JSONObject对象
String request = jsonObject.getString("request");--提取出key为request的value
JSONObject itemd = JSONObject.fromObject(request);--将属性为string的request的value再次转为JSONObject,为了下一步再次提取下一层的value
String items = itemd.getString("item");--提取key为item的value
JSONObject item = JSONObject.fromObject(items);--将items转为JSONObject
通过item.getInt("shelfLife")或者itemd.getString("ownerCode");来提取所需的value
如果遇到多条数据为'XX':[{...},{...}]形势的以下方法处理
例如
提取到最后key为item的String字符串为"item":[{"itemName":"熊孩子新疆无花果成品268g","itemType":"ZC","barCode":"6924459400256","shelfLife ":0,"itemCode":"xhzwhggcp_268"},{"itemName":"好孩子新疆无花果成品268g","itemType":"ZC","barCode":"6924459400256","shelfLife ":1,"itemCode":"xhzwhggcp_268"}]
用下面方法先获取到value值vendorDO.getString("item")获取的值和vendorDO.getJSONArray("item")是一样的,但是前者类型为String,后者是JSONArray,为了使用后面的转换方法,必须用JSONArray格式的
JSONArray ents = vendorDO.getJSONArray("item");
List<Item> ss = (List<Item>)JSONArray.toList(ents,Item.class);---将value转成list对象
for(Item x:ss){System.out.println(x.getItemName());}---提取即可
发送json:
package com.suneee.scn.wms.web.rocketmq; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.rocketmq.client.exception.MQBrokerException; import org.apache.rocketmq.client.exception.MQClientException; import org.apache.rocketmq.remoting.exception.RemotingException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.suneee.scn.message.model.MsgInfo; import com.suneee.scn.message.send.MQProducer; import com.suneee.scn.message.send.MQSend; import com.suneee.scn.wms.consumer.impl.OrderConsumer; import com.suneee.scn.wms.model.dbo.OrderDO; import com.suneee.scn.wms.model.dbo.OrderDetailDO; import com.suneee.scn.wms.model.dbo.ShiplabelDO; @Controller("deliveryOrderSendController") public class DeliveryOrderSendController { private static final Logger log=LoggerFactory.getLogger(DeliveryOrderSendController.class); @Autowired private MQProducer producer; @Autowired private MQSend msgSend; @Autowired private OrderConsumer orderConsumer; //@Scheduled(cron="0/50 * * * * ? ") //间隔5秒执行 public void taskCycle(){ log.debug("【执行定时器开始............发货单!】"); MQSend mqs = new MQSend(); mqs.setProducer(producer.getProducer()); MsgInfo mi = new MsgInfo(); mi.setTopic("WmsTopic"); mi.setType("deliveryOrderConfirm"); //----------------------------------------------------------- //1.先去sp_order_main查出ordernumber,storeordernumber,clientcode,status等属性 List<OrderDO> sodlist = orderConsumer.findOrderNumber(); //2.循环list for(OrderDO sod:sodlist){ StringBuilder sb = new StringBuilder(); String ordernumber = sod.getOrdernumber(); String storeordernumber = sod.getStoreordernumber(); int enterpriseid = sod.getEnterpriseid(); //2.1 去shippinglabel查出barcode,carrier,weight ShiplabelDO shiplabelDO = orderConsumer.queryShiplabelDOByOrderNumber(ordernumber); String logisticsCode = shiplabelDO.getCarriercode(); String expressCode = shiplabelDO.getShiplabel(); Long weight = shiplabelDO.getWeight(); sb.append("{'request': {'deliveryOrder': {'enterpriseid': "+enterpriseid+",'deliveryOrderCode': ' "+storeordernumber+" ','deliveryOrderId': ' "+ordernumber+" ','warehouseCode': 'SunEee01','orderType': 'JYCK','status':'DELIVERED','outBizCode': ' "+ordernumber+" '},"); sb.append(" 'packages': {'package': {'logisticsCode': ' "+logisticsCode+" ','expressCode': ' "+expressCode+" ','weight': ' "+weight+" '}},"); sb.append(" 'orderLines': {'orderLine': [ "); //2.2 去orderdetail查出itemnumber,qty List<OrderDetailDO> sendlist = orderConsumer.selectDeliveryOrderSendMessage(ordernumber); for(OrderDetailDO send :sendlist){ Long actualQty = send.getQty(); String itemCode = send.getItemnumber(); String uom = send.getUom(); sb.append(" {'itemCode': ' "+itemCode+" ','actualQty': '"+actualQty+" ','unit':'"+uom+"'},"); } sb.deleteCharAt(sb.length()-1); sb.append("]}}}"); mi.setData(sb.toString()); try { mqs.sendMsg(mi); log.debug("【单号为"+ordernumber+"的发货单确认接口发送成功!---发送的JSON内容为---"+sb+"】"); orderConsumer.changeOrderStatusByOrderNumber(ordernumber,enterpriseid); log.debug("【单号为"+ordernumber+"的发货单在sp_order_main表的状态更改成功!"); } catch (UnsupportedEncodingException | MQClientException | RemotingException | MQBrokerException | InterruptedException e) { e.printStackTrace(); } } //----------------------------------------------------------- } }
注意:核心就是用StringBuilder的append方法拼接,这样的方法在复杂的多层json时比用对象包裹对象最后转json要方便的多
StringBuilder sb = new StringBuilder();