首页 > 基础资料 博客日记

【Jackson】在Java项目中使用Jackson解析JSON字符串

2024-09-11 14:00:08基础资料围观145

文章【Jackson】在Java项目中使用Jackson解析JSON字符串分享给大家,欢迎收藏Java资料网,专注分享技术知识

在Java中,Jackson库是一个非常流行和强大的JSON处理库。它提供了简洁易用的API,可以用于将Java对象序列化为JSON字符串,以及将JSON字符串反序列化为Java对象。在下面的案例中,我们将详细演示如何使用Jackson包解析JSON字符串。

如何使用Jackson包解析JSON字符串

为了展示如何使用Jackson来解析JSON,我们将进行以下步骤:

  1. 引入Jackson库
  2. 定义一个简单的Java类
  3. 将JSON字符串解析为Java对象
  4. 从JSON字符串解析复杂的嵌套结构
  5. 处理JSON数组
  6. 从Java对象生成JSON字符串

1. 引入Jackson库

在Java项目中使用Jackson库,你需要将相关的依赖添加到项目中。如果你使用Maven项目,可以在pom.xml中添加以下依赖:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>

如果使用Gradle,则需要在build.gradle中添加:

implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2'

2. 定义一个简单的Java类

在这一步,我们将定义一个简单的Java类来表示我们希望解析的JSON结构。假设我们有一个表示用户信息的JSON:

{
  "name": "John Doe",
  "age": 30,
  "email": "john.doe@example.com"
}

为此,我们可以创建一个名为User的Java类:

// User.java
public class User {
    private String name;
    private int age;
    private String email;

    // 构造方法
    public User() {}

    // Getter和Setter方法
    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 getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    // 重写toString方法,便于打印对象信息
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                '}';
    }
}

3. 将JSON字符串解析为Java对象

接下来,我们将使用Jackson库将上面的JSON字符串解析为User对象。

import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonExample {
    public static void main(String[] args) {
        // JSON字符串
        String json = "{\"name\": \"John Doe\", \"age\": 30, \"email\": \"john.doe@example.com\"}";

        // 创建ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 将JSON字符串解析为User对象
            User user = objectMapper.readValue(json, User.class);

            // 打印解析得到的User对象
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4. 从JSON字符串解析复杂的嵌套结构

假设我们有一个更复杂的JSON结构,其中包含嵌套对象,例如:

{
  "name": "John Doe",
  "age": 30,
  "email": "john.doe@example.com",
  "address": {
    "street": "123 Main St",
    "city": "Springfield",
    "zip": "12345"
  }
}

我们可以为Address类创建一个新的Java类,然后将其包含在User类中。

// Address.java
public class Address {
    private String street;
    private String city;
    private String zip;

    // 构造方法
    public Address() {}

    // Getter和Setter方法
    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getCity() {
        return city;
    }

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

    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    // 重写toString方法
    @Override
    public String toString() {
        return "Address{" +
                "street='" + street + '\'' +
                ", city='" + city + '\'' +
                ", zip='" + zip + '\'' +
                '}';
    }
}

// User.java
public class User {
    private String name;
    private int age;
    private String email;
    private Address address; // 新增Address字段

    // 构造方法
    public User() {}

    // Getter和Setter方法
    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 getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    // 重写toString方法
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                ", address=" + address +
                '}';
    }
}

现在,我们可以解析包含嵌套结构的JSON字符串:

import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonExample {
    public static void main(String[] args) {
        // 包含嵌套结构的JSON字符串
        String json = """
            {
              "name": "John Doe",
              "age": 30,
              "email": "john.doe@example.com",
              "address": {
                "street": "123 Main St",
                "city": "Springfield",
                "zip": "12345"
              }
            }
            """;

        // 创建ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 将JSON字符串解析为User对象
            User user = objectMapper.readValue(json, User.class);

            // 打印解析得到的User对象
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5. 处理JSON数组

如果我们有一个JSON数组,例如:

[
  {
    "name": "John Doe",
    "age": 30,
    "email": "john.doe@example.com"
  },
  {
    "name": "Jane Smith",
    "age": 25,
    "email": "jane.smith@example.com"
  }
]

我们可以将其解析为User对象的列表:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;

public class JacksonArrayExample {
    public static void main(String[] args) {
        // JSON数组字符串
        String jsonArray = """
            [
              {
                "name": "John Doe",
                "age": 30,
                "email": "john.doe@example.com"
              },
              {
                "name": "Jane Smith",
                "age": 25,
                "email": "jane.smith@example.com"
              }
            ]
            """;

        // 创建ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 将JSON数组字符串解析为List<User>
            List<User> users = objectMapper.readValue(jsonArray, new TypeReference<List<User>>() {});

            // 打印解析得到的User列表
            users.forEach(System.out::println);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

6. 从Java对象生成JSON字符串

Jackson不仅可以将JSON字符串解析为Java对象,还可以将Java对象序列化为JSON字符串。以下是一个简单的例子:

import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonSerializationExample {
    public static void main(String[] args) {
        // 创建User对象
        User user = new User();
        user.setName("John Doe");
        user.setAge(30);
        user.setEmail("john.doe@example.com");

        // 创建ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 将User对象序列化为JSON字符串
            String jsonString = objectMapper.writeValueAsString(user);

            // 打印JSON字符串
            System.out.println(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

完整示例代码

以下是完整示例代码的汇总,包括了所有步骤:

// Address.java
public class Address {
    private String street;
    private String city;
    private String zip;

    // 构造方法
    public Address() {}

    // Getter和Setter方法
    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getCity() {
        return city;
    }

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

    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    // 重写toString方法
    @Override
    public String toString() {
        return "Address{" +
                "street='" + street + '\'' +
                ", city='" + city + '\'' +
                ", zip='" + zip + '\'' +
                '}';
    }
}

// User.java
public class User {
    private String name;
    private int age;
    private String email;
    private Address address; // 新增Address字段

    // 构造方法
    public User() {}

    // Getter和Setter方法
    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 getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    // 重写toString方法
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                ", address=" + address +
                '}';
    }
}

// JacksonExample.java
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;

public class JacksonExample {
    public static void main(String[] args) {
        // 解析简单JSON字符串为User对象
        parseSimpleJson();

        // 解析嵌套JSON字符串为User对象
        parseNestedJson();

        // 解析JSON数组为List<User>
        parseJsonArray();

        // 将User对象序列化为JSON字符串
        serializeObjectToJson();
    }

    public static void parseSimpleJson() {
        // JSON字符串
        String json = "{\"name\": \"John Doe\", \"age\": 30, \"email\": \"john.doe@example.com\"}";

        // 创建ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 将JSON字符串解析为User对象
            User user = objectMapper.readValue(json, User.class);

            // 打印解析得到的User对象
            System.out.println("Simple JSON:");
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void parseNestedJson() {
        // 包含嵌套结构的JSON字符串
        String json = """
            {
              "name": "John Doe",
              "age": 30,
              "email": "john.doe@example.com",
              "address": {
                "street": "123 Main St",
                "city": "Springfield",
                "zip": "12345"
              }
            }
            """;

        // 创建ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 将JSON字符串解析为User对象
            User user = objectMapper.readValue(json, User.class);

            // 打印解析得到的User对象
            System.out.println("Nested JSON:");
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void parseJsonArray() {
        // JSON数组字符串
        String jsonArray = """
            [
              {
                "name": "John Doe",
                "age": 30,
                "email": "john.doe@example.com"
              },
              {
                "name": "Jane Smith",
                "age": 25,
                "email": "jane.smith@example.com"
              }
            ]
            """;

        // 创建ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 将JSON数组字符串解析为List<User>
            List<User> users = objectMapper.readValue(jsonArray, new TypeReference<List<User>>() {});

            // 打印解析得到的User列表
            System.out.println("JSON Array:");
            users.forEach(System.out::println);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void serializeObjectToJson() {
        // 创建User对象
        User user = new User();
        user.setName("John Doe");
        user.setAge(30);
        user.setEmail("john.doe@example.com");

        // 创建ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 将User对象序列化为JSON字符串
            String jsonString = objectMapper.writeValueAsString(user);

            // 打印JSON字符串
            System.out.println("Serialized JSON:");
            System.out.println(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

运行结果

在控制台运行上述代码后,你将看到如下输出:

Simple JSON:
User{name='John Doe', age=30, email='john.doe@example.com', address=null}

Nested JSON:
User{name='John Doe', age=30, email='john.doe@example.com', address=Address{street='123 Main St', city='Springfield', zip='12345'}}

JSON Array:
User{name='John Doe', age=30, email='john.doe@example.com', address=null}
User{name='Jane Smith', age=25, email='jane.smith@example.com', address=null}

Serialized JSON:
{"name":"John Doe","age":30,"email":"john.doe@example.com","address":null}

小结

通过本案例,我们学习了如何使用Jackson库来解析和生成JSON字符串:

  1. 将JSON字符串解析为Java对象
  2. 解析包含嵌套结构的JSON
  3. 解析JSON数组为Java对象列表
  4. 将Java对象序列化为JSON字符串

Jackson库还提供了许多其他功能,如自定义序列化和反序列化、支持JSON流处理等,可以满足各种复杂的JSON处理需求。


文章来源:https://blog.csdn.net/u013675821/article/details/140686755
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云