简体   繁体   English

如何将 JSON 消息的一部分解析为 String 并传递给另一个 class?

[英]How to parse a part of JSON message to String and pass it to another class?

I have following JSON message as a response from server:我有以下 JSON 消息作为服务器的响应:

{
  "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?我只想将“消息”部分解析为 Java 中的一个变量,并将其传递给另一个 class。如何实现?

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

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对于 org.json

you should add a maven dependency你应该添加一个 maven 依赖

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>

Unfortunatly your code example is not complete eg one can not see what kind of Object "res" is.不幸的是,您的代码示例不完整,例如,看不到 Object“res”是什么类型。 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.就像@Melloware 和@asbrodova 说的那样,您可以使用现有的 JSON 解析器,例如 org.json,或者因为您已经逐行遍历消息,所以您可以简单地使用正则表达式来提取消息字符串。

    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 + "'.");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM