在Java中解析JSON字符串通常使用第三方库,比如Jackson、Gson、JSON-java等。下面以Jackson库为例来解析JSON字符串:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.2</version>
</dependency>
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonParser {
public static void main(String[] args) {
String jsonString = "{\"name\": \"Alice\", \"age\": 25}";
try {
ObjectMapper objectMapper = new ObjectMapper();
// 将JSON字符串转换为Map对象
Map<String, Object> jsonMap = objectMapper.readValue(jsonString, new TypeReference<Map<String, Object>>() {});
System.out.println(jsonMap);
// 获取指定字段的值
String name = (String) jsonMap.get("name");
int age = (int) jsonMap.get("age");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上代码将JSON字符串{"name": "Alice", "age": 25}
解析为Map对象,并输出其中的字段值。可以根据实际需求来解析JSON字符串并获取相应的数据。