1

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:)

4
  • please post sample inputs. Jan 31, 2017 at 12:38
  • In your input data is there every any objects as a value to a key? Or will the format always be {key:exact value,key:exact value}
    – CraigR8806
    Jan 31, 2017 at 12:42
  • You can use the split-method with comma to get the key-value-pairs. After that you can use the split-method with colon to get the values.
    – IQV
    Jan 31, 2017 at 12:42
  • 1
    @IQV What if a key or value contains a comma and/or colon? (Trick question; the answer is, regular expressions cannot be used to parse JSON.)
    – VGR
    Jan 31, 2017 at 13:01

2 Answers 2

3

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();
}
0
2

The format looks like JSON. If that's true, use any JSON parser you like and get only the keys.

E.g. org.json:json in Maven Central.

https://github.com/stleary/JSON-java

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.