我正在尝试将 XML 转换为 Json。我在下面找到了这个示例,并且几乎按照我想要的方式工作。但是,有没有办法从我的计算机加载 XML 文件,而不是直接从代码中加载?我找到了一些替代方案,但如果可能的话,我想坚持使用 org.json ......
public static String TEST_XML_STRING = ("C:\\results\\results.xml")
; 或类似的东西?
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
public class Main {
public static int PRETTY_PRINT_INDENT_FACTOR = 4;
public static String TEST_XML_STRING =
"<breakfast_menu>\n"+
"<food>\n"+
"<name>Belgian Waffles</name>\n"+
"<price>$5.95</price>\n"+
"<description>\n"+
"Two of our famous Belgian Waffles with plenty of real maple syrup\n"+
"</description>\n"+
"<calories>650</calories>\n"+
"</food>\n"+
"<food>\n"+
"<name>Strawberry Belgian Waffles</name>\n"+
"<price>$7.95</price>\n"+
"<description>\n"+
"Light Belgian waffles covered with strawberries and whipped cream\n"+
"</description>\n"+
"<calories>900</calories>\n"+
"</food>\n"+
"</breakfast_menu>";
public static void main(String[] args) {
try {JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);
} catch (JSONException e) {
System.out.println(e.toString());
}
}
}
我已经进入了这个,但在第 20 行给了我错误
线程“main”java.lang.Error 中的异常:未解决的编译问题:在 Main.main(Main.java:20)
import java.io.File;
import java.io.FileInputStream;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
public class Main {
File file = new File("teste.xml");
FileInputStream fin = new FileInputStream(file);
byte[] xmlData = new byte[(int) file.length()];
fin.read(xmlData);
fin.close();
public static int PRETTY_PRINT_INDENT_FACTOR = 4;
public static String TEST_XML_STRING = new String(xmlData, "UTF-8");
public static void main(String[] args) {
try {JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);
} catch (JSONException e) {
System.out.println(e.toString());
}
}
}