使用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依赖,可以在pom.xml文件中添加以下内容:

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

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

java 使用hutool工具 String转Json对象再获取属性

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

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