【问题标题】:(Exception in thread "main" org.json) A JSONObject text must begin with '{' at character 1(线程“main”org.json 中的异常)JSONObject 文本必须在字符 1 处以 '{' 开头
【发布时间】:2020-09-02 09:45:21
【问题描述】:

我在读取我的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);
        }

    }

还有我想读取和编辑文件的 addToJson 函数

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:\1PROGRAMMING\Padlock\src\padlock\register\info.json 的字符 1 处以 '{' 开头 **

【问题讨论】:

  • 已经发布了一个答案,如果它对你有用,请告诉我。

标签: java json


【解决方案1】:

我认为它可能将我的 josn 文件读取为字符串,并将“[”定位在错误的索引中,但我需要找到可以将其读取为 Json 元素或直接访问“用户”jsonArray 的方式在里面

【讨论】:

    【解决方案2】:

    你的JSON是正确的,你可以在https://jsonformatter.curiousconcept.com/#验证

    问题出在一行

    JSONObject ar = new JSONObject(path);
    

    因为您的变量 path 的类型为 String JSONObject 不知道它是否是 .json 文件的路径,因此它试图将 &lt;file Location&gt; 解析为 JSON,而您得到的是 JSONParseException 因此出现错误,试试这个

    String text = new String(Files.readAllBytes(Paths.get(fileName)),StandardCharsets.UTF_8);
    JSONObject obj = new JSONObject(text);
    

    【讨论】:

      【解决方案3】:
      public class Foo {
      
          public static void main(String[] args) throws IOException {
              Path path = Paths.get("e:/info.json");
              Map<Long, User> users = loadUsers(path);
              signUp(users);
              saveUsers(path, users);
          }
      
          public static Map<Long, User> loadUsers(Path path) throws IOException {
              JSONObject root = readRootObject(path);
              Map<Long, User> users = new HashMap<>();
      
              if (root != null) {
                  for (Object obj : root.getJSONArray("users")) {
                      JSONObject json = (JSONObject)obj;
      
                      User user = new User();
                      user.setId(json.getLong("id"));
                      user.setEmail(json.getString("email"));
                      user.setName(json.getString("name"));
                      user.setSecondName(json.getString("secondName"));
                      user.setId(json.getInt("age"));
                      user.setPassword(json.getString("password"));
      
                      users.put(user.getId(), user);
                  }
              }
      
              return users;
          }
      
          public static void saveUsers(Path path, Map<Long, User> users) throws IOException {
              JSONObject root = Optional.ofNullable(readRootObject(path)).orElseGet(JSONObject::new);
              root.put("users", users.values());
      
              try (Writer writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
                  writer.write(root.toString(2));
              }
          }
      
          private static JSONObject readRootObject(Path path) throws IOException {
              if (!Files.isReadable(path))
                  return null;
      
              try (Reader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
                  return new JSONObject(new JSONTokener(reader));
              }
          }
      
          public static void signUp(Map<Long, User> users) {
              try (Scanner scan = new Scanner(System.in)) {
                  User user = new User();
                  System.out.print("Enter age: ");
                  user.setAge(scan.nextInt());
      
                  if (user.getAge() < 18)
                      throw new RuntimeException("You must be more than 18 years old.");
      
                  System.out.print("Enter email: ");
                  user.setEmail(scan.next());
      
                  System.out.print("Enter name: ");
                  user.setName(scan.next());
      
                  System.out.print("Enter second name: ");
                  user.setSecondName(scan.next());
      
                  System.out.print("Enter password: ");
                  user.setPassword(scan.next());
      
                  user.setId(System.nanoTime());
                  users.put(user.getId(), user);
              }
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2015-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-15
        相关资源
        最近更新 更多