简体   繁体   English

如何将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;
}

How to deserialize Json data_user to java object User? 如何反序列化Json data_user到Java对象User?

I tried with Gson : 我尝试过Gson:

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

But I have an error with this code because the Json contains a school which hasn't the school's name. 但是我在此代码上有一个错误,因为Json包含一所没有该学校名称的学校。

How Can I serialize the Json to java Object? 如何将Json序列化为Java Object?

School.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 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 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);
    }
}

Result 结果

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

Try with the Jackson Library. 尝试使用杰克逊图书馆。 With Gson with should have not any problem, I tried with the code of @Saurabh and it work well 与Gson一起应该没有任何问题,我尝试使用@Saurabh的代码,并且效果很好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM