在 Java 中,您可以使用 JSON 库来解析 JSON 字符串并获取其中某个属性的值。常用的 JSON 库包括 Gson 和 Jackson。

以下是使用 Gson 库的示例代码:

import com.google.gson.Gson;

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

        Gson gson = new Gson();
        Person person = gson.fromJson(jsonString, Person.class);

        String name = person.getName();
        System.out.println('Name: ' + name);
    }
}

class Person {
    private String name;
    private int age;
    private String city;

    // Getter and Setter methods

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

在上述代码中,我们首先定义了一个 Person 类,其中包含了与 JSON 字符串对应的属性。然后,我们使用 Gson 的 fromJson() 方法将 JSON 字符串转换为 Person 对象。最后,通过调用 Person 对象的相应 getter 方法,我们可以获取到所需属性的值。

如果使用 Jackson 库,代码示例如下:

import com.fasterxml.jackson.databind.ObjectMapper;

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

        ObjectMapper objectMapper = new ObjectMapper();
        Person person = objectMapper.readValue(jsonString, Person.class);

        String name = person.getName();
        System.out.println('Name: ' + name);
    }
}

class Person {
    private String name;
    private int age;
    private String city;

    // Getter and Setter methods

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

在上述代码中,我们使用了 Jackson 库的 readValue() 方法将 JSON 字符串转换为 Person 对象,然后通过调用 Person 对象的相应 getter 方法来获取属性的值。

Java 获取 JSON 字符串属性值:Gson 和 Jackson 库示例

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

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