java如何解析json字符串

小億
85
2024-04-19 10:09:14
欄目: 編程語言

在Java中解析JSON字符串通常使用第三方庫,比如Jackson、Gson、JSON-java等。下面以Jackson庫為例來解析JSON字符串:

  1. 添加Jackson庫的依賴:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.2</version>
</dependency>
  1. 使用ObjectMapper類來解析JSON字符串:
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字符串轉(zhuǎn)換為Map對(duì)象
            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對(duì)象,并輸出其中的字段值??梢愿鶕?jù)實(shí)際需求來解析JSON字符串并獲取相應(yīng)的數(shù)據(jù)。

0