在字符串中查找JSON对象

时间:2012-11-20 08:28:52

标签: java android regex json

在我关于me having to deal with a poorly implemented chat server的问题后,我得出的结论是,我应该尝试从其他服务器响应中获取聊天消息。

基本上,我收到的字符串看起来像这样:

13{"ts":2135646,"msg":"{\"ts\":123156,\"msg\":\"this is my chat {message 1\"}","sender":123,"recipient":321}45{"ts":2135646,"msg":"{\"ts\":123156,\"msg\":\"this is my chat} message 2\"}","sender":123,"recipient":321}1

我想要的结果是两个子串:

{"ts":2135646,"msg":"{\"ts\":123156,\"msg\":\"this is my chat {message 1\"}","sender":123,"recipient":321}
{"ts":2135646,"msg":"{\"ts\":123156,\"msg\":\"this is my chat} message 2\"}","sender":123,"recipient":321}

我可以接收的输出是JSON对象(可能包含其他JSON对象)和一些数字数据之间的混合。

我需要从该字符串中提取JSON对象。

我已经考虑过计算花括号来选择第一个开口和相应的关闭之间的内容。但是,消息可能包含大括号。

我已经考虑过正则表达式,但我无法得到一个可行的(我不擅长正则表达式)

有关如何进行的任何想法?

1 个答案:

答案 0 :(得分:1)

这应该有效:

List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile(
    "\\{           # Match an opening brace.                              \n" +
    "(?:           # Match either...                                      \n" +
    " \"           #  a quoted string,                                    \n" +
    " (?:          #  which may contain either...                         \n" +
    "  \\\\.       #   escaped characters                                 \n" +
    " |            #  or                                                  \n" +
    "  [^\"\\\\]   #   any other characters except quotes and backslashes \n" +
    " )*           #  any number of times,                                \n" +
    " \"           #  and ends with a quote.                              \n" +
    "|             # Or match...                                          \n" +
    " [^\"{}]*     #  any number of characters besides quotes and braces. \n" +
    ")*            # Repeat as needed.                                    \n" +
    "\\}           # Then match a closing brace.", 
    Pattern.COMMENTS);
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    matchList.add(regexMatcher.group());
}