mardi 10 mars 2020

JSONObject can't read attribute from existing object even though object is correctly instanced

I have problem with reading json attribute even though object correctly instanced.

First, I send json from client side with JavaScript:

let object = {
        firstName: document.getElementById("firstName").value,
        lastName: document.getElementById("lastName").value,
        username: document.getElementById("username").value,
        password: document.getElementById("password").value,
        email: document.getElementById("email").value,
        action: "registration"
}

let request = new XMLHttpRequest();
...

On server side I have code:

req.setCharacterEncoding("UTF-8");
    JSONObject jsonObject = null;

    // String address = "/WEB-INF/pages/login.jsp";
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = req.getReader();
        while ((line = reader.readLine()) != null)
            jb.append(line);
    } catch (Exception e) {
        /* report an error */ }

    try {
        jsonObject = HTTP.toJSONObject(jb.toString());
    } catch (JSONException e) {
        // crash and burn
        throw new IOException("Error parsing JSON request string");
    }

    String action = jsonObject.getString("firstName");

jsonObject exists but program throws org.json.JSONException: JSONObject["firstName"] not found.

Object on server side when I use debugger: enter image description here




Aucun commentaire:

Enregistrer un commentaire