xml2json 转换

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String xml="M201505210848255000.000.5zhuxiaolongzhuxiaolong10123 http://mobaopay.com/callback.do订单";
        JSONObject json= null;
        try {
            json = XmlUtil.xml2JSON(xml.getBytes());
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(json.toJSONString());
    }
}


import com.alibaba.fastjson.JSONObject;

import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by [email protected] on 2015/5/19.
 */
public class XmlUtil {
    public static JSONObject xml2JSON(byte[] xml) throws JDOMException, IOException {
        JSONObject json = new JSONObject();
        InputStream is = new ByteArrayInputStream(xml);
        SAXBuilder sb = new SAXBuilder();
        org.jdom2.Document doc = sb.build(is);
        Element root = doc.getRootElement();
        json.put(root.getName(), iterateElement(root));
        return json;
    }

    private static JSONObject iterateElement(Element element) {
        List node = element.getChildren();
        Element et = null;
        JSONObject obj = new JSONObject();
        List list = null;
        for (int i = 0; i < node.size(); i++) {
            list = new LinkedList();
            et = (Element) node.get(i);
            if (et.getTextTrim().equals("")) {
                if (et.getChildren().size() == 0)
                    continue;
                if (obj.containsKey(et.getName())) {
                    list = (List) obj.get(et.getName());
                }
                list.add(iterateElement(et));
                obj.put(et.getName(), list);
            } else {
                if (obj.containsKey(et.getName())) {
                    list = (List) obj.get(et.getName());
                }
                list.add(et.getTextTrim());
                obj.put(et.getName(), list);
            }
        }
        return obj;
    }
}


所需jar包

fastjson-1.1.36.jar
jdom-2.0.2.jar

打印结果

System.out: {"MoBaoAccount":{"Commission":["0.5"],"CustParam":["123"],"MerchID":["zhuxiaolong1"],"NotifyUrl":["http://mobaopay.com/callback.do"],"OrderNo":["M20150521084825"],"TradeAmt":["5000.00"],"TradeSummary":["订单"],"UserID":["zhuxiaolong"],"tradeType":["0"]}}

你可能感兴趣的:(xml2json 转换)