String json = "{'name': 'Tom','array':[{'a':'111','b':'222','c':'333'},{},{'a':'999'}],'address':'York'}";
try {
JSONObject jsonObject = JSONObject.fromObject(json);
String name = jsonObject.getString("name");
String address = jsonObject.getString("address");
System.out.println("name is:" + name);
System.out.println("address is:" + address);
JSONArray jsonArray = jsonObject.getJSONArray("array");
for (int i = 0; i < jsonArray.size(); i++) {
System.out.println("item " + i + " :" + jsonArray.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
一切都好。
但是当我输入 {'name': 'Tom','array':[{'a':'111','b':'222','c':'333'},{}, {'a':'999'}],'address':'York'}
到文件中。
File file = new File(fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString = reader.readLine()) != null){
JSONObject jo = JSONObject.fromObject(tempString.trim());
String id = jo.getString("id");
String name = jo.getString("name");
log.info(id + ":" + name);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
它告诉我线程“main”中的异常net.sf.json.JSONException:JSONObject文本必须以“{”在“{'name':'Tom','array'的字符1处以'{'开头: [{'a':'111','b':'222','c':'333'},{},{'a':'999'}],'地址':'约克'}
。这段代码有什么问题?谁能帮我解决一下吗?谢谢。
我的文件:
{'name': 'Tom','array':[{'a':'111','b':'222','c':'333'},{},{ 'a':'999'}],'地址':'约克'}
最佳答案
来自评论:
I use
InputStreamReader isr = new InputStreamReader(new FileInputStream(fileName), "UTF-8"); reader = new BufferedReader(isr); String tempString = null; while ((tempString = reader.readLine()) != null){
, and my file starts with
EE BB BF
, I've checked.
问题是该文件以 BOM 开头。 JSON 解码器期望文件以可以启动 JSON 类型的字符开头,但它得到的是 U+FEFF。
JSON 文件最好不以 BOM 开头。
如果您必须处理这种情况,那么您可以使用缓冲区来完成:
BufferedReader buf = new BufferedReader(isr);
// remove BOM
buf.mark(1);
if(buf.read() != '\uFEFF') {
buf.reset();
}
// continue...
关于java - 无法解析 jsonobject--- -"A JSONObject text must begin with ' {' at character 1 of ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24926739/