[开发|java] java 将json转化java对象

  1. 使用Jackson库将JSON转换为Java对象:
    安装依赖

<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-coreartifactId>
    <version>2.12.5version>
dependency>


<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
    <version>2.12.5version>
dependency>

代码示例:

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonToObjectUsingJackson {
    public static void main(String[] args) {
        String jsonString = "{\"name\": \"John\", \"age\": 30, \"email\": \"[email protected]\"}";

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

            System.out.println("Name: " + person.getName());
            System.out.println("Age: " + person.getAge());
            System.out.println("Email: " + person.getEmail());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Java类,用于映射JSON数据
    public static class Person {
        private String name;
        private int age;
        private String email;

        // 省略构造函数、getter和setter方法
        // 注意:字段名和JSON中的键名必须匹配,或者使用注解@JsonProperty指定映射关系
    }
}
  1. 使用Gson库将JSON转换为Java对象:
    安装依赖
<dependency>
    <groupId>com.google.code.gsongroupId>
    <artifactId>gsonartifactId>
    <version>2.8.9version>
dependency>

代码示例:

import com.google.gson.Gson;

public class JsonToObjectUsingGson {
    public static void main(String[] args) {
        String jsonString = "{\"name\": \"John\", \"age\": 30, \"email\": \"[email protected]\"}";

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

            System.out.println("Name: " + person.getName());
            System.out.println("Age: " + person.getAge());
            System.out.println("Email: " + person.getEmail());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Java类,用于映射JSON数据
    public static class Person {
        private String name;
        private int age;
        private String email;

        // 省略构造函数、getter和setter方法
        // 注意:字段名和JSON中的键名必须匹配
    }
}

你可能感兴趣的:(开发,JAVA,java,json,开发语言)