要将 String 类型的 JSON 转换为 net.sf.json.JSONObject 对象,您可以使用 net.sf.json.JSONObject 的静态方法 fromObject()。以下是示例代码:

import net.sf.json.JSONObject;

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

        JSONObject jsonObject = JSONObject.fromObject(jsonString);

        // 使用JSONObject对象进行操作
        String name = jsonObject.getString('name');
        int age = jsonObject.getInt('age');

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

在上面的示例中,我们首先定义了一个 String 类型的 jsonString,它包含了一个名为 'name' 的字符串属性和一个名为 'age' 的整数属性。然后,我们使用 net.sf.json.JSONObject 的静态方法 fromObject() 将 jsonString 转换为 net.sf.json.JSONObject 对象。接下来,我们可以使用 JSONObject 对象的方法获取属性值并进行操作。

请注意,您需要将 net.sf.json 库添加到您的项目中以使用 net.sf.json.JSONObject 类。

Java 中使用 net.sf.json 将 String 转换为 JSONObject

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

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