java,从给定字符串中截取出连续的json字符串,且字符串中必须包含metricName字段
时间: 2024-02-20 17:57:56 浏览: 31
可以在上一个回答的基础上,加入对 `metricName` 字段的判断。
假设给定字符串为 `str`,则可以使用以下代码来截取出连续的json字符串,且字符串中必须包含 `metricName` 字段:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.alibaba.fastjson.JSONObject;
public class JsonSubstring {
public static void main(String[] args) {
String str = "some text {\"name\":\"John\",\"metricName\":\"metric1\",\"value\":30,\"city\":\"New York\"} some text {\"name\":\"Mary\",\"value\":25,\"city\":\"Los Angeles\"} some text {\"name\":\"Tom\",\"metricName\":\"metric2\",\"value\":40,\"city\":\"Chicago\"} some text";
Pattern pattern = Pattern.compile("\\{.*?\\}"); // 匹配 { 和 } 之间的内容
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
String jsonStr = matcher.group();
JSONObject jsonObj = JSONObject.parseObject(jsonStr);
if (jsonObj.containsKey("metricName")) {
String metricName = jsonObj.getString("metricName");
System.out.println(jsonStr);
}
}
}
}
```
运行以上代码,输出结果为:
```
{"name":"John","metricName":"metric1","value":30,"city":"New York"}
{"name":"Tom","metricName":"metric2","value":40,"city":"Chicago"}
```
这样就可以从给定字符串中截取出连续的json字符串,且字符串中必须包含 `metricName` 字段了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)