我正在创建一个独立的java程序。我有创建CSV文件的代码,当我把它作为字符串变量(例如:下面)
时,它可以工作this.btnCreateFile = new JButton("Create File");
this.btnCreateFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblOutput.setText(textArea.getText());
String jsonString = "{\"infile\": [{\"field1\": 11,\"field2\": 12,\"field3\": 13},{\"field1\": 21,\"field2\": 22,\"field3\": 23},{\"field1\": 31,\"field2\": 32,\"field3\": 33}]}";
JSONObject output;
try {
output = new JSONObject(jsonString);
JSONArray docs = output.getJSONArray("infile");
File file=new File("/tmp2/fromJSON.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
但是,当我将JSON字符串更改为从textArea获取时,它会显示' JSONObject文本必须以' {'在1 [字符2第1行]' (例如:在下面)
this.btnCreateFile = new JButton("Create File");
this.btnCreateFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblOutput.setText(textArea.getText());
JSONObject output;
try {
output = new JSONObject(textArea);
JSONArray docs = output.getJSONArray("infile");
File file=new File("/tmp2/fromJSON.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
有没有人知道如何解决这个问题?感谢
这是JSON字符串:
{"infile": [{"field1": 11,"field2": 12,"field3": 13},
{"field1": 21,"field2": 22,"field3": 23},
{"field1": 31,"field2": 32,"field3": 33}]}
答案 0 :(得分:0)
尝试更改此行
output = new JSONObject(textArea);
到
output = new JSONObject(textArea.getText());
我还建议打印输出:
textArea.getText()
答案 1 :(得分:-1)
可能无法检测到文本{
。保持花括号的逃脱特征。