Search code examples
javaajaxjsonservletsjson-simple

Access values of JSON objects from a JSON array in Servlet (JAVA)


I am stuck here for two days, trying to read values of JSONobjects stored in JSONArray. I use JSON simple, its not helping out alot! I only can get to the JSONArray elemts that hold the JSONObjects by something like this jsonstring=JSONArrayName.get(indx); but then I cant read values from the JSON object stored in "jsonstring" string Please help!! please find my code below.

ps: I am using $.ajax, I need to store the values received and process/use it in my server

// here is my client side code Login.html


//My servlet code to process json received from client 
BufferedReader reader = request.getReader();
StringBuilder myinputholder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
    myinputholder.append(line);
}

Object obj = JSONValue.parse(myinputholder.toString());
JSONArray newjsonarr = (JSONArray) obj;
     //  JSONObject newjson= (JSONObject) newjsonarr.get(0); // this line causes errors 
PrintWriter pw = response.getWriter();
String f = JSONValue.toJSONString(newjsonarr.get(0));// this will give me a json object 
         // proper format but I cant do anything with the values inside

JSONValue.writeJSONString(f, pw); // this is only for troubleshooting 

Solution

  • I changed the library to Jackson and it worked prefectly fine. I had to make some tweaks to my String tho, I had to remove the quotes in the beginning of the string and the ones at the end "{}" then I had to replace all {} backslashes exist with space to get a valid string format { "Key": "Value", "Key":,"Value"} because my string looked like "{ \"Key\": \"Value\", \"Key\":,\"Value\"}\". I could extract each value of each key sent from the client side. find the code below.

        String uname="";
        String pass="";
        BufferedReader reader = request.getReader();
        StringBuilder myinputholder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            myinputholder.append(line);
        }
    
        Integer s= myinputholder.length();
    
        String ss= myinputholder.toString();
        String sss= ss.substring(1, s-1); // this is to avoid the beginning and end "{}"
        sss=sss.replace("\\", ""); \\ this line is to replace all \ with space
        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getJsonFactory();
        JsonParser jp = factory.createJsonParser(sss);
        JsonNode actualObj = mapper.readTree(jp);
        JsonNode subnode= actualObj.path("username");
        JsonNode subnode2= actualObj.path("password");
        uname= subnode.getTextValue();
        pass=actualObj.get("password").getTextValue();