zoukankan      html  css  js  c++  java
  • 对象转为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\"?>", ""));取到的中文是乱码

  • 相关阅读:
    [转]ThinkPHP中如何使用原生SQL
    php定时回调接口
    [转]mysql dual虚拟表
    [转]mysql变量使用总结
    [转]使用mysql profiles 来查看sql 语句执行计划
    [转]Mysql中的SQL优化与执行计划
    [转]MySQL单列索引和组合索引的区别介绍
    前端开发框架
    sugar crm
    [转]MCC(移动国家码)和 MNC(移动网络码)
  • 原文地址:https://www.cnblogs.com/zyfxlv/p/2872955.html
Copyright © 2011-2022 走看看