2014-07-08 52 views
-1

我想将JSON对象转换为XML文档。如何将JSON对象转换为UTF-8格式的XML

下面是代码,注意我想输出格式为的UTF-8格式的XML。

package com.test.json; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileReader; 

import org.json.JSONObject; 
import org.json.XML; 

public class ConvertJSONtoXML { 

    public static void main(String[] args) throws Exception { 

    BufferedReader jsonBuffer = new BufferedReader(new FileReader(new File("C:\\Users\\test\\Desktop\\sample-json.json"))); 
    String line = null; 
    String json=""; 
    while((line=jsonBuffer.readLine())!=null){ 
     json+=line; // here we have all json loaded 
    } 

    JSONObject jsonObject = new JSONObject(json); 

    System.out.println(XML.toString(jsonObject)); // here we have XML Code 

    jsonBuffer.close(); 

    } 
} 

谁能请在此帮助。我有泰文字符的JSON数据。

+2

我强烈建议不要使用'FileReader'开始 - 这将始终使用平台默认编码。使用具有特定编码的'InputStreamReader'。哦,不要像这样的循环中执行字符串连接... –

+0

感谢您的答复。我是新来的Java。你可以请指导如何做到这一点.. – user2650241

+1

哪部分?你看过“InputStreamReader”的文档吗?还要注意,在写入控制台时,它可能不支持所有想要的字符......而是将其写入文件(使用'OutputStreamWriter',并指定UTF-8作为编码)。 –

回答

1

更新你的类使用InputStreamReader代替FileReader因为InputStreamReader S可采取的编码字符集作为第二个构造函数参数:

public class ConvertJSONtoXML 
{ 
    public static void main(String[] args) throws Exception 
    { 
    File jsonFile = new File("C:\\Users\\test\\Desktop\\sample-json.json"); 
    InputStreamReader reader = new InputStreamReader(new FileInputStream(jsonFile), "UTF-8"); 
    BufferedReader jsonBuffer = new BufferedReader(reader); 
    String line; 
    StringBuilder json = new StringBuilder(); 
    while ((line = jsonBuffer.readLine()) != null) 
    { 
     json.append(line); // here we have all json loaded 
    } 
    JSONObject jsonObject = new JSONObject(json.toString()); 
    System.out.println(XML.toString(jsonObject)); // here we have XML Code 
    jsonBuffer.close(); 
    } 
} 

的代码也已更新为使用StringBuilder用于json令牌串联。

+0

对不起,我无法在此发布代码。我编辑了原始问题。我在限制发布代码的同时回答,因为我是这个论坛的新手。再次感谢您的帮助。 – user2650241

+0

你能提供你的输出吗? * ??? *标记出现在控制台中? 我可以成功转换您提供的文件为json enry。 – tmarwen

+1

谢谢,我能够用uTF-8在一个文件中编写xml,但问题在于它只能打印json的第一个对象。它应该迭代并将json的所有对象转换为xml文件。 – user2650241