java正则 json
时间: 2023-09-07 16:17:34 浏览: 47
使用Java正则表达式来处理JSON数据是不太方便的,因为JSON格式比较复杂,需要考虑到各种情况。建议使用Java自带的JSON解析库来处理JSON数据,例如:
1. 使用org.json包
```java
import org.json.*;
String jsonStr = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
JSONObject obj = new JSONObject(jsonStr);
String name = obj.getString("name");
int age = obj.getInt("age");
String city = obj.getString("city");
```
2. 使用com.fasterxml.jackson包
```java
import com.fasterxml.jackson.databind.*;
String jsonStr = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonStr);
String name = node.get("name").asText();
int age = node.get("age").asInt();
String city = node.get("city").asText();
```
以上两种方法都可以很方便地解析JSON数据,不需要使用正则表达式。