要将一个JSON字符串转换为JSONObject对象,可以使用JSON库提供的方法。在Java中,常用的JSON库有org.json和com.google.gson等。

使用org.json库的示例代码如下:

import org.json.JSONObject;

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

        // 将JSON字符串转换为JSONObject对象
        JSONObject jsonObject = new JSONObject(jsonString);

        // 使用JSONObject对象获取属性值
        String name = jsonObject.getString("name");
        int age = jsonObject.getInt("age");
        String city = jsonObject.getString("city");

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

使用com.google.gson库的示例代码如下:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

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

        // 使用JsonParser解析JSON字符串
        JsonParser jsonParser = new JsonParser();
        JsonObject jsonObject = jsonParser.parse(jsonString).getAsJsonObject();

        // 使用JsonObject对象获取属性值
        String name = jsonObject.get("name").getAsString();
        int age = jsonObject.get("age").getAsInt();
        String city = jsonObject.get("city").getAsString();

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

以上两种方法都可以将JSON字符串转换为JSONObject对象,并可以通过对象的方法获取JSON属性值。选择使用哪种方法取决于个人的喜好和项目的需求。

java8 json String转为jsonObject

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

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