سؤال

I'm using a Json file to save some informations about users with this code:

Login login = new Login(email, token, jsessionId);

            JSONObject jsonObj = new JSONObject();

            JSONObject userDetail = new JSONObject();

            JSONArray listFiles = new JSONArray();

            userDetail.put("email", email);
            token = EncodeUtil.encode(token);
            userDetail.put("token", token);
            userDetail.put("files", listFiles);

            try {

                if (!(file.exists())) {

                    JSONArray userDetails = new JSONArray();
                    userDetails.add(userDetail);
                    jsonObj.put("users", userDetails);

                    FileWriter fileWriter = new FileWriter(file);
                    fileWriter.write(jsonObj.toString());
                    fileWriter.flush();
                    fileWriter.close();

                } else {

                    boolean emailExists = true;

                    JSONParser parser = new JSONParser();
                    Object obj = parser.parse(new FileReader(file));
                    JSONObject jsonObjReader = (JSONObject) obj;
                    JSONArray jsonArrayWriter = (JSONArray) jsonObjReader.get("users");
                    int length = jsonArrayWriter.size();
                    for (int i = 0; i < length; i++) {
                        Object currentObj = jsonArrayWriter.get(i);
                        JSONObject currentJson = (JSONObject) currentObj;
                        String email2 = (String) currentJson.get("email");
                        if (email2.equals(email)) {
                            emailExists = true;
                        } else {
                            emailExists = false;
                        }
                    }

                    if (!emailExists) {
                        jsonArrayWriter.add(userDetail);
                        jsonObj.put("users", jsonArrayWriter);
                        FileWriter fileWriter = new FileWriter(file);
                        fileWriter.write(jsonObj.toString());
                        fileWriter.flush();
                        fileWriter.close();
                    }
                }

            } catch (Exception e) {

                Logger.getLogger(LoginLocalServiceImpl.class.getName()).log(Level.SEVERE, e.getMessage());

                throw new PortalException("Erro ao ler Json File");
            }

It works fine and return me a JSON with this structure:

{"users":[
      {"files":[],
       "token":"XXXX",
       "email":"XXXX"}
     ]
}

Then I try to add some informations in files[] array with this code above:

try {

                JSONObject fileRef = new JSONObject();
                fileRef.put("date", date);
                fileRef.put("type", type);
                fileRef.put("name", name);

                JSONParser parser = new JSONParser();
                Object obj = parser.parse(new FileReader(file));

                JSONObject jsonObjReader = (JSONObject) obj;
                JSONArray jsonArrayUsers = (JSONArray) jsonObjReader.get("users");

                for (int i = 0; i < jsonArrayUsers.size(); i++) {
                    JSONObject jsonTest = (JSONObject) jsonArrayUsers.get(i);
                    String emailTest = (String) jsonTest.get("email");
                    if (emailTest.equals(email)) {
                        JSONArray jsonArrayFiles = (JSONArray) jsonTest.get("files");
                        jsonArrayFiles.add(fileRef);
           //             jsonTest.put("files", jsonArrayFiles);
           //             jsonArrayUsers.add(jsonTest);
           //             jsonObjReader.put("users", jsonArrayUsers);

                        //            System.out.println(jsonArrayFiles.toString());

                    }
                }
                FileWriter fileWriter = new FileWriter(file);
                fileWriter.write(jsonObjReader.toString());
                fileWriter.flush();
                fileWriter.close();

            } catch (IOException ex) {
                Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParseException ex) {
                Logger.getLogger(MainViewController.class.getName()).log(Level.SEVERE, null, ex);
            }

My json file now is showing what I want:

{"users":[
      {"files":[
            {"name":"d9f6cd671a384fe59bae29e2718463b5",
             "type":"Apresentação",
             "date":Sat Feb 09 13:48:32 GMT-03:00 2013}
           ],
       "email":"XXXX",
       "token":"XXXX"
      }
     ]
}

No problem until here. But when I try to load my json again with the first code using JSONParser it can't be read, why?? Everything seems to be all right :(

هل كانت مفيدة؟

المحلول

The date should be surrounded by quotes

{
    "users": [{
        "files":[{
            "name":"d9f6cd671a384fe59bae29e2718463b5",
            "type":"Apresentação",
            "date":"Sat Feb 09 13:48:32 GMT-03:00 2013"
        }],
        "email":"XXXX",
        "token":"XXXX"
    }]
}

نصائح أخرى

I'm assuming the malformed date string is a typo as the library is not going to produce that output. I note that you are writing code points with values beyond U+007F.

FileWriter fileWriter = new FileWriter(file);

The above line is defective on any system that does not use a Unicode Transformation Format (UTF) as its default encoding. The documentation states:

The constructors of this class assume that the default character encoding

The same issue is present in FileReader. Both types should be avoided.

JSON mandates Unicode:

JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.

If you need to provide character data directly to the JSON API you are using, then you must specify the encoding.

Reading:

try (InputStream in = new FileInputStream(filename);
     Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
  // read from stream
}

Writing:

try (OutputStream out = new FileOutputStream(filename);
     Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
  // write to stream
}

This is Java 7 code, but the same principles apply in earlier versions. See here for a rough guide to character encoding in Java. The reading mechanism is incomplete as it does not detect which UTF is being used - refer to the spec for the necessary byte-pattern detection.

As a commenter noted, it is insufficient to say "it's not working!" - you must detail the nature of the failure. Java developers expect an error stack trace.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top