Ignacio Chiazzo Ignacio Chiazzo - 5 months ago 9
Java Question

How to convert JsonString to Java Object

I have a Json string:

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


The classes school and user are :

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?

I tried with Gson :

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


But I have an error with this code because the jsonString contains a school which hasn't the school's name.

How Can I serialize the Json to java Object?

Answer

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

Result

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