天天看点

JSONObject text must begin with '{' at character 1 of错误解决

问题描述

如下代码,读取本地文件,将文本内容使用org.json解析为jsonobject对象,结果一直(catch到)爆出如题错误。

JSONObject text must begin with '{' at character 1 of错误解决
StringBuilder sb=new StringBuilder();
        BufferedReader br=new BufferedReader(new FileReader("d:/total.json"));
        String s = null;
        while((s = br.readLine())!=null){//使用readLine方法,一次读一行
            sb.append(s);
        }
        JSONObject jsonObject2=null;
        String string=sb.toString().replaceAll(" ", "").trim();
        System.out.println(string);
        try {
            jsonObject2=new JSONObject(string);

        } catch (Exception e) {
            // TODO Auto-generated catch block      

解决方案

经查证,文本内容确实没有问题,print的字符串符合json语法(可以到​​http://www.bejson.com/​​ 在线检测),最后发现是文件保存的格式如BOM问题。

JSONObject text must begin with '{' at character 1 of错误解决