如何将 Json 转换为 Java 对象,反序列化 Json

How to convert Json to Java Object, Deserializing Json

data_user = "{"id":1,"lastName":"lastName","name":"name","school":{"id":1}}"

public class School {
     private int id;
     private String name;
}

public class User {
     private int id;
     private String lastName;
     private String name;
     private School school;
}

如何将 Json data_user 反序列化为 java 对象 User?

我试过 Gson :

 Gson gson = new Gson();
 User user = gson.fromJson(data_user, User.class)

但是我的代码有错误,因为 Json 包含一所没有学校名称的学校。

如何将 Json 序列化为 java 对象?

School.java

public class School {
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "School [id=" + id + ", name=" + name + "]";
    }
}

User.java

public class User {
    private int id;
    private String lastName;
    private String name;
    private School school;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public School getSchool() {
        return school;
    }
    public void setSchool(School school) {
        this.school = school;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", lastName=" + lastName + ", name=" + name
                + ", school=" + school + "]";
    }
}

Main.java

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.testgson.beans.User;

public class Main {
    private static Gson gson;

    static {
        gson = new GsonBuilder().create();
    }

    public static void main(String[] args) {
        String j = "{\"id\":1,\"lastName\":\"lastName\",\"name\":\"ignacio\",\"school\":{\"id\":1}}";
        User u = gson.fromJson(j, User.class);
        System.out.println(u);
    }
}

结果

User [id=1, lastName=lastName, name=ignacio, school=School [id=1, name=null]]

试试 Jackson 图书馆。使用 Gson 应该没有任何问题,我尝试使用@Saurabh 的代码并且它运行良好