Java 使用 Hutool 工具将字符串转换为 JSON 对象并获取属性

本文将介绍如何使用 Hutool 工具将字符串转换为 JSON 对象,并获取属性值。

示例代码

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class Main {
    public static void main(String[] args) {
        String jsonString = '{"name":"John", "age":30, "city":"New York"}';

        // 将字符串转换为Json对象
        JSONObject jsonObject = JSONUtil.parseObj(jsonString);

        // 获取属性值
        String name = jsonObject.getStr('name');
        int age = jsonObject.getInt('age');
        String city = jsonObject.getStr('city');

        System.out.println('name: ' + name);
        System.out.println('age: ' + age);
        System.out.println('city: ' + city);
    }
}

上述代码中,首先使用 JSONUtil.parseObj() 方法将字符串转换为 Json 对象。然后,通过 getStr()getInt() 方法获取属性的值。

添加 Hutool 依赖

在运行代码之前,需要先添加 Hutool 依赖,可以在 pom.xml 文件中添加以下内容:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.10</version>
</dependency>

这样就可以使用 Hutool 工具来操作 Json 对象了。

Java 使用 Hutool 工具将字符串转换为 JSON 对象并获取属性

原文地址: https://www.cveoy.top/t/topic/qDEY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录