java中json操作xml和生成xml

java代码:
package com.syz;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import org.json.JSONObject;
import org.json.XML;

public class Test {  
    public static void main(String[] args) {  
        BufferedReader buffRed=null;  
        BufferedWriter buffWri=null;  

        try{  
            //将XML转换成JSON  
            String fileName1="json.xml";  
            buffRed=new BufferedReader(new FileReader(fileName1));  
            String tempStr;  
            StringBuffer xmlStrBuff=new StringBuffer();  
            while((tempStr=buffRed.readLine())!=null)  
            xmlStrBuff.append(tempStr);  
            JSONObject syz=XML.toJSONObject(xmlStrBuff.toString());
            System.out.println("syz="+syz.getInt("syz"));
            System.out.println("JSON str="+syz);  
           
            //将JSON转换成XML  
	        //String jsonStr="{Heros:{FBI:[{name:\"rose\",age:\"24\"},{name:\"jack\",age:\"25\"}],NBA:[{name:\"tom\",sex:\"man\"},{name:\"jack\",sex:\"women\"}]}};";  
            String jsonStr="{syz:2};";  
            String fileName2="json.xml";  
            buffWri=new BufferedWriter(new FileWriter(fileName2));  
            JSONObject jsonObj=new JSONObject(jsonStr);  
            buffWri.write("<?xml version=\"1.0\" encoding=\"GBK\"?>");  
            buffWri.newLine();  
            buffWri.write("<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">");  
            buffWri.newLine();  
            buffWri.write(XML.toString(jsonObj));  
            buffWri.flush();  

            System.out.println("run end!");  
        }catch(Exception e){  
            e.printStackTrace();  
        }finally{  
            try{  
                if(buffRed!=null)  
                    buffRed.close();  
                if(buffWri!=null)  
                    buffWri.close();  
            }catch(Exception e){  
                e.printStackTrace();  
            }  
        }  
    }  
}
json.xml:
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<syz>2</syz>

执行后控制台打印:

syz=2
JSON str={"syz":"2"}
run end!


json.jar包下载地址:http://download.csdn.net/detail/shiyuezhong/4574245


如果是在src\main\resources下的xml则通过以下方法取得:

String fileName1 = Thread.currentThread().getContextClassLoader().getResource("jsonxml.xml").getPath();  
 fileName1=fileName1.substring(1, fileName1.length());

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值