import org.json.JSONObject;
public class StringToJsonExample {
public static void main(String[] args) {
// 定义一个JSON格式的字符串
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
// 将字符串转换为JSONObject对象
JSONObject jsonObject = new JSONObject(jsonString);
// 输出JSONObject对象的内容
System.out.println(jsonObject.toString(4)); // 使用缩进格式化输出
}
}
org.json.JSONObject
类,这个类提供了将字符串转换为JSON对象的功能。jsonString
。new JSONObject(jsonString)
将字符串转换为JSONObject
对象。toString(4)
方法以缩进格式输出JSON对象的内容,其中4
表示缩进4个空格。如果你没有安装org.json
库,可以通过Maven或Gradle添加依赖,或者手动下载jar包。
上一篇:java缓存
下一篇:java在线编辑器
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站