1

I have following JSON message as a response from server:

{
  "HttpStatus": 500,
  "Errors": [
    {
      "ErrorCode": 325267273,
      "Message": "Object too old",
      "ParameterName": null
    }
  ]
}

Getting the response:

  if (res.getStatus() == 200) {
    return true;
  } else {
    LogManager.getLogger(INIT_LOGGER).error(String.format("%d", res.getStatus()));
    BufferedReader rdr = new BufferedReader(new InputStreamReader((InputStream) res.getEntity()));
    StringBuilder sbr = new StringBuilder();
    while ((msg = rdr.readLine()) != null) {
      sbr.append(msg);
      System.out.println("Faces message 1: " + msg);
    }
    return false;

I would like to parse just the "Message" part to a variable in Java and pass it to another class. How to achieve this?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
WScoder
  • 93
  • 1
  • 8
  • Does this answer your question? [Parsing JSON in Java with org.Json?](https://stackoverflow.com/questions/19483891/parsing-json-in-java-with-org-json) – Melloware Apr 12 '21 at 12:06
  • Unfortunately no. The messages i recieve from server vary. I would need to use the Message part as an object. – WScoder Apr 12 '21 at 12:13

3 Answers3

1

If it's guarantied that your string only contains one "Message" tag you could try getting the index of that and parsing the string that follows (for efficiency not building the whole string):

while ((msg = rdr.readLine()) != null) {
    int i = msg.indexOf("\"Message\":");

    // If not contained, continue with next line
    if (i == -1)
        continue;

    i += 10; // Add length of searched string to reach end of match

    // Skip all whitespace
    while (Character.isWhitespace(msg.charAt(i)))
        i++;

    // If following is a string
    if (msg.charAt(i++) == '"') {
        StringBuilder sb = new StringBuilder();
        char c;

        // While not reached end of string
        for (; (c = msg.charAt(i)) != '"'; i++) {
            // For escaped quotes and backslashes; could be made a lot simpler without
            if (c == '\\')
                sb.append(msg.charAt(++i));
            else sb.append(c);
        }

        messageString = sb.toString();
    }
}
linux_user36
  • 113
  • 1
  • 8
0

you could do following

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String status = obj.getString("HttpStatus");

JSONArray arr = obj.getJSONArray("Errors");
for (int i = 0; i < arr.length(); i++)
{
    String errorCode = arr.getJSONObject(i).getString("ErrorCode");
    ......
}

...

For org.json

you should add a maven dependency

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>
asbrodova
  • 36
  • 9
0

Unfortunatly your code example is not complete e.g. one can not see what kind of Object "res" is. Like @Melloware and @asbrodova said you could use existing JSON parser like org.json or since you already loop through the message line by line you could simply use a regex in order to extract the message string.

    String extractedString = "";
    String strLine = "\"Message\": \"Object too old\",";
    Pattern MESSAGE_PATTERN = Pattern.compile("(?i)^.*?\"Message\"\\:\\s*?\"(.*?)\".*?\\Z");
    Matcher m = MESSAGE_PATTERN.matcher(strLine);

    if (m.find()) {
        extractedString = m.group(1);
        System.out.println("Found: '" + extractedString + "'.");
    }
  • It is not really needed to know, for example the "res" object to asnwer the question. In this case the important task was to parse the "msg" variable. Apologies if i was unclear in presenting the question. – WScoder Apr 12 '21 at 13:59