当前位置: 首页 > 知识库问答 >
问题:

(线程“main”org.json中的异常)JSONObject文本必须以字符1处的“{”开头

蒋茂
2023-03-14

我很难在以下目录中读取我的json文件:E:\1Programming\padlock\src\padlock\register\info.json

{
  "users": [
    {
      "Email": "3",
      "Second Name": "2",
      "Age": "123",
      "Name": "1",
      "Password": "4"
    }
  ]
}

问题是,每次我试图将内容文件作为json对象读取时,都会出现类似文章标题的错误。主要思想是读取这个json文件,在我的json对象中的“users”数组中添加一个新用户,并创建一个基本的本地用户数据库。

private static void  SignUp() throws IOException, JSONException, ParseException {
        //System.out.println("SignUp");
        String path = "E:\\1PROGRAMMING\\Padlock\\src\\padlock\\register\\info.json";
        String[] labels = {"Age","Name","Second Name","Email","Password"};
        ArrayList<String> dataUser = new ArrayList<>();

      
        Scanner scanner = new Scanner(System.in);

        //check if value Integer
        System.out.println(labels[0]);
        int age = Integer.parseInt(scanner.nextLine());

        if( age >= 18) {
            dataUser.add(Integer.toString(age)); //adding age data to arraylist as first data

            for (int element =1;element< labels.length;element++){ //adding rest of data
                System.out.println(labels[element]);
                String data = scanner.nextLine();
                dataUser.add(data);
            }
            /////////////////////////////////////////////////
            //Spring data request to Python serverless
            /////////////////////////////////////////////////

            System.out.println(dataUser);

            //Add to JSON file
            File exists = new File(path);
            if (exists.exists()) {//check if json exists
                System.out.println("File found.");
                //addToJson()
                addToJson(path, dataUser); //HERE IS THE PROBLEM
            }else{
                System.out.println("File not found... Creating File with the new user");
                //createJson()
                createJson(path, dataUser, labels);
                //createJson(path, name, secondName,age,email,password);
            }
        }else {
            System.out.println("You must be more than 18 years old.");
            System.exit(0);
        }

    }
private static void addToJson(String path, ArrayList<String> dataUser) throws IOException, ParseException, JSONException {
        //create jsonobject to add in our path file
        
        //read path file content
        JSONObject ar = new JSONObject(path);

        for (int i = 0; i < ar.length(); i++) {
            System.out.println( "Name: " + ar.getString("Password") );
        }
        
        //Add jsonobject created into our path file

    }

**线程“main”org.json.jsonException中的异常:JSONObject文本必须在E的字符1处以“{”开头:\1programming\padlock\src\padlock\register\info.json**

共有1个答案

诸葛煜
2023-03-14

我认为这可能是因为它将我的josn文件作为字符串读取,并将“[”定位在错误的索引中,但我需要找到将其作为Json元素读取或直接访问其中的“users”jsonArray的方法

 类似资料: