Search code examples
javaalgorithmstringbuffer

How to print the values of a dictionary-like StringBuffer in java?


I have this code :

StringBuffer sb = new StringBuffer();
try {
   BufferedReader reader = request.getReader();
   String line = null;
   while ((line = reader.readLine()) != null) {
      sb.append(line);
      System.out.println(line);
   }
} catch (Exception e) {
   e.printStackTrace();
}

the line :

System.out.println(line);

prints in console at the end of the loop like this:

{"signupname":"John","signuppassword":"1234","signupnickname":"Jonny",    
"signupdescription":"student","signupphoto":"(here photo url)"}

how can I get only the values of the keys? I want something like this: John 1234 Jonny student (here photo url)

Thanks for helpers:)


Solution

  • If each row is a complete JSON object. You can use Gson JSON parser.

    https://mvnrepository.com/artifact/com.google.code.gson/gson

    StringBuffer sb = new StringBuffer();
    try {
      BufferedReader reader = request.getReader();
      String line;
      Gson gson = new Gson();
      while ((line = reader.readLine()) != null) {
        Map map = gson.fromJson(line, Map.class);
        for(Object value : map.values()) {
          System.out.println(value);
        }
        sb.append(line);
        System.out.println(line);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }