如何将JSON对象转换为UTF-8格式的XML

时间:2014-07-08 12:15:38

标签: java xml json java-ee utf-8

我正在尝试将JSON对象转换为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数据。

1 个答案:

答案 0 :(得分:0)

更新您的班级以使用InputStreamReader代替FileReader,因为InputStreamReader可以将编码字符集作为第二个构造函数参数:

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令牌连接。