webservices转json工具类(凑合用吧)

package com.gdpass.health.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.*;

import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Xml2JsonUtils {


    //测试
    public static void main(String[] args) throws Exception {


        String xmlStr= "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
                "    <soap:Body>" +
                "        <BloodcostsinfoResponse xmlns=\"http://microsoft.com/webservices/\">" +
                "            <BloodcostsinfoResult>{\"code\":0,\"msg\":null,\"count\":2,\"data\":[{\"useBloodZfAmount\":0,\"reductionId\":\"ceeedfdc5fca404da7bc0f3490bcf639\",\"shBloodBankName\":\"北海市中心血站\",\"patientId\":\"38e02c6336604f9181e09932a631f30a\",\"reductionBlood\":300.00,\"identityIdName\":\"[450521196910107545]\",\"identityTypeName\":\"居民身份证\",\"shBloodUserId\":\"579f1c20-1344-476b-b765-b71c346f2c68\",\"bxfs\":2.0,\"bhReason\":null,\"shState\":2,\"donationBloodPeopleZj\":\"450521199204047331\",\"qtjg\":null,\"useBloodPeopleDonationBlood\":6.0,\"reductionDate\":\"2021-02-10 11:47:36\",\"tel\":\"18077975119\",\"pzNo\":\"0000820287\",\"patientName\":\"李凤连\",\"orderNo\":\"481889\",\"ybybBlood\":0,\"reductionAmount\":660.00,\"donationBloodPeople\":\"符善智\",\"sex\":\"女性\",\"useBloodDate\":\"2021-01-27\",\"bxfsName\":\"居民医保\",\"shPeopleTel\":null,\"multipleBlood\":600.00,\"settlementDate\":\"\",\"shBloodUserPhone\":\"13367699366\",\"hospitalName\":\"合浦县人民医院\",\"bxhAmount\":6044.78,\"shBloodUserName\":\"王华连\",\"handlePeople\":\"李华丽\",\"shType\":1,\"gx\":\"父母\",\"otherAmount\":0.00,\"shPeople\":\"李华丽\",\"sbbxAmount\":5872.46,\"allAmount\":11917.24,\"reimbursementPeople\":\"李凤连\",\"useBloodAmount\":1485.00,\"identityId\":\"450521196910107545\",\"jgdm\":\"4505210015\",\"useBlood\":5.50,\"reductionNo\":\"桂E-20210210-3-3\"},{\"useBloodZfAmount\":0,\"reductionId\":\"fab4ac74995741f0a21420caf4e17396\",\"shBloodBankName\":\"北海市中心血站\",\"patientId\":\"58d3f38332134d3190bab5106dbc687b\",\"reductionBlood\":400.00,\"identityIdName\":\"[450525195507266934]\",\"identityTypeName\":\"居民身份证\",\"shBloodUserId\":\"579f1c20-1344-476b-b765-b71c346f2c68\",\"bxfs\":2.0,\"bhReason\":null,\"shState\":2,\"donationBloodPeopleZj\":\"450521198602056933\",\"qtjg\":null,\"useBloodPeopleDonationBlood\":6.0,\"reductionDate\":\"2021-02-01 11:43:14\",\"tel\":\"13878906886\",\"pzNo\":\"0000819845\",\"patientName\":\"夏月宏\",\"orderNo\":\"482281\",\"ybybBlood\":0,\"reductionAmount\":880.00,\"donationBloodPeople\":\"夏春河\",\"sex\":\"男性\",\"useBloodDate\":\"2021-01-27\",\"bxfsName\":\"居民医保\",\"shPeopleTel\":null,\"multipleBlood\":800.00,\"settlementDate\":\"\",\"shBloodUserPhone\":\"13367699366\",\"hospitalName\":\"合浦县人民医院\",\"bxhAmount\":4075.90,\"shBloodUserName\":\"王华连\",\"handlePeople\":\"李华丽\",\"shType\":1,\"gx\":\"父母\",\"otherAmount\":0.00,\"shPeople\":\"李华丽\",\"sbbxAmount\":3247.34,\"allAmount\":7323.24,\"reimbursementPeople\":\"夏月宏\",\"useBloodAmount\":2345.00,\"identityId\":\"450525195507266934\",\"jgdm\":\"4505210015\",\"useBlood\":4.50,\"reductionNo\":\"桂E-20210201-1-1\"}]}</BloodcostsinfoResult>" +
                "        </BloodcostsinfoResponse>" +
                "    </soap:Body>" +
                "</soap:Envelope>";
        Document doc= DocumentHelper.parseText(xmlStr);
        JSONObject json=new JSONObject();
        dom4j2Json(doc.getRootElement(),json);
        Object jsonObject = json.getJSONObject("Body").getJSONObject("BloodcostsinfoResponse").get("BloodcostsinfoResult");
        Map mapType = JSON.parseObject(jsonObject.toString(),Map.class);
        System.out.println(mapType);
    }

    private static void resolveXml(String response,JSONArray jsonArray) throws DocumentException {
        //response替换掉whilexml
        String whilexml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<Data>" +
                "<Status>1</Status>" +
                "<SucceedCount>1</SucceedCount>" +
                "<ErrorCount>1</ErrorCount>" +
                "<Info>" +
                "<Succeed>" +
                "<Record KeyFieldValue =\"联网系统中的主键值\">" +
                "<dCode>dCode</dCode>" +
                "</Record>" +
                "<Record KeyFieldValue =\"联网系统中的主键值\">" +
                "<dCodeNum>主键字段值</dCodeNum>" +
                "</Record>" +
                "</Succeed>" +
                "<Error>" +
                "<Record>" +
                "<dIDCardNo>144058319920226281X</dIDCardNo>" +
                "<dId>1118153944</dId>" +
                "<ErrorMessage>错误信息1111</ErrorMessage>" +
                "</Record>" +
                "<Record>" +
                "<dIDCardNo>244058319920226281X</dIDCardNo>" +
                "<dId>1118153933</dId>" +
                "<ErrorMessage>错误信息222</ErrorMessage>" +
                "</Record>" +
                "<Record>" +
                "<dIDCardNo>344058319920226281X</dIDCardNo>" +
                "<dId>1118153922</dId>" +
                "<ErrorMessage>错误信息333</ErrorMessage>" +
                "</Record>" +
                "<Record>" +
                "<dIDCardNo>444058319920226281X</dIDCardNo>" +
                "<dId>1118153944</dId>" +
                "<ErrorMessage>错误信息444</ErrorMessage>" +
                "</Record>" +
                "</Error>" +
                "<Exception>" +
                "异常消息11111" +
                "</Exception>" +
                "</Info>" +
                "</Data>";
        Document docforwhile= DocumentHelper.parseText(whilexml);
        JSONObject jsonforwhile=new JSONObject();
        dom4j2Json(docforwhile.getRootElement(), jsonforwhile);
        JSONObject jsonError = jsonforwhile.getJSONObject("Info").getJSONObject("Error");
        if(jsonError!=null){
            JSONArray jsonObject = jsonError.getJSONArray("Record");
            List<Map<String,Object>> responseList = new ArrayList<>(jsonObject.size());
            for (int i = 0; i < jsonObject.size(); i++) {
                JSONObject o = (JSONObject) jsonObject.get(i);
                Map<String,Object> map = new HashMap<>();
                for (Map.Entry<String, Object> entry : o.entrySet()) {
                    map.put(entry.getKey(),entry.getValue());
                }
                responseList.add(map);
            }
            List<Map<String,Object>> uploadList = new ArrayList<>(jsonArray.size());
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject o = (JSONObject) jsonArray.get(i);
                for (Map.Entry<String, Object> entry : o.entrySet()) {
                    Map<String,Object> map = new HashMap<>();
                    map.put(entry.getKey(),entry.getValue());
                    uploadList.add(map);
                }
            }
            List<Map<String,Object>> list = new ArrayList<>();
            //上传的属性值
            for (int i = 0; i < responseList.size(); i++) {
                for (Map.Entry<String, Object> resp : responseList.get(i).entrySet()) {
                    for (int i1 = 0; i1 < uploadList.size(); i1++) {
                        for (Map.Entry<String, Object> req : uploadList.get(i1).entrySet()) {
                              if(req.getKey().equalsIgnoreCase(resp.getKey())){
                                  if(req.getValue().equals(resp.getValue())){
                                      System.out.println(req.getKey()+"---->"+req.getValue()+"---->错误信息为:"+responseList.get(i).get("ErrorMessage"));
                                  }
                              }
                        }
                    }
                }
            }

        }

    }

    public static String readFile(String path) throws Exception {
        File file=new File(path);
        FileInputStream fis = new FileInputStream(file);
        FileChannel fc = fis.getChannel();
        ByteBuffer bb = ByteBuffer.allocate(new Long(file.length()).intValue());
        //fc向buffer中读入数据
        fc.read(bb);
        bb.flip();
        String str=new String(bb.array(),"UTF8");
        fc.close();
        fis.close();
        return str;

    }
    /**
     * xml转json
     * @param xmlStr
     * @return
     * @throws DocumentException
     */
    public static JSONObject xml2Json(String xmlStr) throws DocumentException {
        Document doc= DocumentHelper.parseText(xmlStr);
        JSONObject json=new JSONObject();
        dom4j2Json(doc.getRootElement(), json);
        return json;
    }

    /**
     * xml转json
     * @param element
     * @param json
     */
    public static void dom4j2Json(Element element, JSONObject json){
        //如果是属性
        for(Object o:element.attributes()){
            Attribute attr=(Attribute)o;
            if(!isEmpty(attr.getValue())){
                json.put("@"+attr.getName(), attr.getValue());
            }
        }
        List<Element> chdEl=element.elements();
        if(chdEl.isEmpty()&&!isEmpty(element.getText())){//如果没有子元素,只有一个值
            json.put(element.getName(), element.getText());
        }

        for(Element e:chdEl){//有子元素
            if(!e.elements().isEmpty()){//子元素也有子元素
                JSONObject chdjson=new JSONObject();
                dom4j2Json(e,chdjson);
                Object o=json.get(e.getName());
                if(o!=null){
                    JSONArray jsona=null;
                    if(o instanceof JSONObject){//如果此元素已存在,则转为jsonArray
                        JSONObject jsono=(JSONObject)o;
                        json.remove(e.getName());
                        jsona=new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if(o instanceof JSONArray){
                        jsona=(JSONArray)o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                }else{
                    if(!chdjson.isEmpty()){
                        json.put(e.getName(), chdjson);
                    }
                }


            }else{//子元素没有子元素
                for(Object o:element.attributes()){
                    Attribute attr=(Attribute)o;
                    if(!isEmpty(attr.getValue())){
                        json.put("@"+attr.getName(), attr.getValue());
                    }
                }
                if(!e.getText().isEmpty()){
                    json.put(e.getName(), e.getText());
                }
            }
        }
    }

    public static boolean isEmpty(String str) {

        if (str == null || str.trim().isEmpty() || "null".equals(str)) {
            return true;
        }
        return false;
    }


    private static JSONObject getJsonObject(String body) throws DocumentException {
        Document bodyDoc;
        bodyDoc = DocumentHelper.parseText(body);
        JSONObject jsonBody = new JSONObject();
        Xml2JsonUtils.dom4j2Json(bodyDoc.getRootElement(), jsonBody);
        return jsonBody;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值