使用JAVA将任意封装对象转换成JSON、XML文件与对象之间的相互转化

使用JAVA将任意封装对象转换成JSON、XML文件与对象之间的相互转化

新学的一些实用小技巧,记录下来,以便忘记
本文共两个使用点
  1. XML文件与对象之间的相互转化
  2. 将任意封装对象转换成JSON格式

1、XML文件与对象之间的相互转化

1、实现将xml格式的文件转换成实体对象。
    1.1 读取xml文件,得到String类型的xml字符串
    1.2 将xml字符串转换成实体对象
2、将实体对象转换成xml文件
    2.1 将实体对象转换成xml格式字符串
    2.2 将xml字符串写入xml文件

我们先来看看xml文档和封装对象实体的格式

//xml文件内容格式

<?xml version='1.0' encoding='UTF-8'?>
<ROOT>
    <id>1</id>
    <cityName>北京</cityName>
</ROOT>
//城市实体对象,这里只贴封装成员变量

public class City {
    private int id;
    private String cityName;

    public City() {
    }
    //。。。。setter和getter
    //省略
}
//代码1实现,从xml转换成对象

public City xmlToObject()
    {
        //创建City实例
        City city = new City();
        try {
            StringBuilder sb = new StringBuilder();
            //读取tmp.xml文件,并将其存入StringBuilder中得到xml字符串
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("tmp.xml")));
            String src ;
            while ((src=br.readLine())!=null)
            {
                sb.append(src);
            }
            //得到xml字符串
            String xml = sb.toString();
            //读取xml的字符流
            StringReader sr = new StringReader(xml);
            //将字符流转换成输入流,方便dom解析xml
            InputSource is = new InputSource(sr);
            //利用DOM工厂创建DOM解析实例
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            //利用dom实例,解析xml文件
            Document document = documentBuilder.parse(is);
            //得到对应ID结点列表
            NodeList idNode = document.getElementsByTagName("id");
            //若id结点列表不为空,则给城市信息赋值
            if (idNode.item(0) != null) {
                city.setId(Integer.valueOf(idNode.item(0).getTextContent()));
            }
            NodeList cityNameNode = document.getElementsByTagName("cityName");
            if (cityNameNode.item(0) != null) {
                city.setCityName(cityNameNode.item(0).getTextContent());
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

            return city;
    }
//代码2实现,将对象转换成xml文件

    /**
     * 转换成xml
     */
    public String toXml(City city) {
        StringBuffer xml = new StringBuffer();
        xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        xml.append("<ROOT>\n");
        xml.append("\t<id>" + city.getId() + "</id>\n");
        xml.append("\t<cityName>" + city.getCityName() + "</cityName>\n");
        xml.append("</ROOT>");
        return xml.toString();
    }

2、将任意对象转换成JSON格式

实现功能:将任意封装实体bean转换成json格式。
所需jar包:Fastjson--1.2.32
 <!--Maven引入-->
 <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.39</version>
        </dependency>
//实现功能。将对象转换成json字符串

    @Test
    public void toJson()
    {   
        //通过第一步,将xml文件转换,得到城市对象
        City city = xmlToObject();
        //将对象转换成json格式的字符串
        String cityJson = JSON.toJSONString(city);

        System.out.println(cityJson); //输出结果为---  {"cityName":"北京","id":1}
    }

如果对您有帮助,请帮忙点击一下赞 ^^

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值