對象轉為xml輸出到頁面,中文亂碼問題


本項目是一個webseriice的客戶端項目

Action 類:

SearchHotelRQ reqobj = XmlObjUtil.xml2Obj(reqstr, SearchHotelRQ.class);
            SearchHotelRS searchHotelRS = port.searchHotel(reqobj);
            resxml = XmlObjUtil.objToXmlString(searchHotelRS);
            return resxml;

對象轉為xml的方法:objToXmlString

public static <T> String objToXmlString(T obj) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(obj.getClass());
        Marshaller m = jc.createMarshaller();
        m.setProperty("jaxb.formatted.output", true);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Result result = new StreamResult(out);
        m.marshal(obj, result);
        //轉碼
        byte[] bystr = out.toByteArray();
        String str = "";
        try {
             str = new String(bystr,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StringBuffer sb = new StringBuffer(str.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", ""));
        //log.error("JAXB transform object to string without version: "+ sb.toString());
        return sb.toString();
    }

第一種轉碼方式(在網上找的):  m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");但在我這個項目中不起作用,不知為什么

第二種:上面方法中轉碼那一步,如果不轉碼,直接這么寫的話,StringBuffer sb = new StringBuffer(new String(out.toByteArray()).replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", ""));取到的中文是亂碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM