要将 String 转换为 Json 对象(JSONObject),你需要使用 json 库(如 json.org 或 Gson)提供的方法。下面是一个示例代码,使用 json.org 库将 String 转换为 JSONObject:

import org.json.*;

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

        JSONObject jsonObject = new JSONObject(jsonString);

        System.out.println(jsonObject.toString());
    }
}

这个例子中,我们先定义了一个包含 json 格式的 String 对象(jsonString)。然后使用 JSONObject 的构造函数将 jsonString 转换为 JSONObject 对象(jsonObject)。最后,我们使用 toString() 方法将 JSONObject 对象转换为 String 并打印出来。

请注意,你需要在项目中引入 json.org 库的 jar 文件才能运行这个示例代码。

Java String 转 Json 对象(JSONObject) 示例

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

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